patterns

The Proxy Pattern

The Proxy Pattern is probably the most influential design pattern for C++. The Proxy provides a placeholder for accessing another object.

patterns

 

The proxy pattern is one of the seven structural patterns from the book “Design Patterns: Elements of Reusable Object-Oriented Software”. A proxy controls access to another object, allowing you to perform additional operations before or after you access the original object. Sound familiar?

Which idiom is characteristic of C++? Right: RAII (Resource Acquisition Is Initialization). RAII is the C++ way to implement the Proxy Pattern. Here are the facts about the Proxy Pattern.

Proxy Pattern

Purpose

  • Provides a placeholder for accessing another object.

Also Known As

  • Surrogate

Use Case

  • Control access to another object
    • Remote proxy (acts as an intermediary for a remote service)
    • Virtual proxy (creates an object lazily on request)
    • Security proxy (adds security to a request)
    • Caching proxy (delivers cached requests)

Structure

Proxy

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

Be part of my mentoring programs:

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (starts March 2024)
  • Do you want to stay informed: Subscribe.

     

     

    Proxy

    • Controls the access and lifetime of the RealSubject
    • Supports the same interface as RealSubject

    Subject

    • Defines the interface of the Proxy and the RealSubject

    RealSubject

    • Implements the interface

    Example

    The following examples use two generic proxies: std::unique_ptr and std::shared_ptr.

    // proxy.cpp
    
    #include <iostream>
    #include <memory>
    
    class MyInt{
     public:
        MyInt(int i):i_(i){}
        int getValue() const {
            return i_;
        }
     private:
        int i_;
    };
    
    int main(){
    
        std::cout << '\n';
    
        MyInt* myInt = new MyInt(1998);                     // (3)
        std::cout << "myInt->getValue(): " << myInt->getValue() << '\n';
    
        std::unique_ptr<MyInt> uniquePtr{new MyInt(1998)};  // (1)
        std::cout << "uniquePtr->getValue(): " << uniquePtr->getValue() << '\n';
    
        std::shared_ptr<MyInt> sharedPtr{new MyInt(1998)};  // (2)
        std::cout << "sharedPtr->getValue(): " << sharedPtr->getValue() << '\n';
    
        std::cout << '\n';
    
    }
    

     

    Both smart pointers can transparently access the member function getValue of MyInt. It makes no difference if you call the member function getValue on the std::unique_ptr, (line 1) on the std::shared_ptr, (line 2), or on the object directly. All calls return the same value:

     proxy

    Known Uses

    The smart pointers model the Proxy Pattern in C++. Additionally, the RAII Idiom is the C++ adaption of the Proxy Pattern. RAII is the crucial idiom in C++. I will write more about it in a few lines.

    Related Patterns

    • The Adaptor Pattern adjusts an existing interface, but the Facade creates a new simplified interface.
    • The Decorator Pattern is structurally similar to the Proxy, but the Decorator has a different purpose. A Decorator extends an object with additional responsibilities. A Proxy controls access to an object.
    • The Facade Pattern is similar to the Proxy because it encapsulates access to an object. The Facade does not support the same interface as the Proxy but supports a simplified one.

    Pros and Cons

    Pros

    • The underlying object is fully transparent to the client.
    • The proxy can answer requests directly without using the client
    • The proxy can be transparently extended or replaced with another proxy.

    Cons

    • The separation of the proxy and the object makes the code more difficult
    • The forwarded proxy calls may be performance critical

    RAII Idiom

    RAII stands for Resource Acquisition Is Initialization. The most crucial idiom in C++ is that a resource should be acquired in the constructor and released in the object’s destructor. The key idea is that the destructor will automatically be called if the object goes out of scope. Or, to put it differently: A resource’s lifetime is bound to a local variable’s lifetime, and C++ automatically manages the lifetime of locals.

    There is one big difference between the Proxy Pattern and the RAII Idiom in C++. In the classical Proxy Pattern, the Proxy and the RealObject (object) implement the same interface. Therefore, you invoke a member function on the proxy, and this call is delegated to the object. On the contrary, it is typical for RAII to do the operation on the object implicitly.

    The following example shows the deterministic behavior of RAII in C++.

    // raii.cpp
    
    #include <iostream>
    #include <new>
    #include <string>
    
    class ResourceGuard{
      private:
        const std::string resource;
      public:
        ResourceGuard(const std::string& res):resource(res){
          std::cout << "Acquire the " << resource << "." <<  '\n';
        }
        ~ResourceGuard(){
          std::cout << "Release the "<< resource << "." << '\n';
        }
    };
    
    int main() {
    
      std::cout << '\n';
    
      ResourceGuard resGuard1{"memoryBlock1"};              // (1)
    
      std::cout << "\nBefore local scope" << '\n';
      {
        ResourceGuard resGuard2{"memoryBlock2"};            // (3)
      }                                                     // (4)
      std::cout << "After local scope" << '\n';
      
      std::cout << '\n';
    
      std::cout << "\nBefore try-catch block" << '\n';
      try{
          ResourceGuard resGuard3{"memoryBlock3"};
          throw std::bad_alloc();                          // (5)
      }   
      catch (std::bad_alloc& e){                           // (6)
          std::cout << e.what();
      }
      std::cout << "\nAfter try-catch block" << '\n';
      
      std::cout << '\n';
    
    }                                                     // (2)
    

     

    ResourceGuard is a guard that manages its resource. In this case, the string stands for the resource. ResourceGuard creates in its constructor the resource and releases the resource in its destructor. It does its job very decent.

    The destructor of resGuard1 (line 1) is called at the end of the main function (line 2). The lifetime of resGuard2 (line 3) already ends in line 4. Therefore, the destructor is automatically executed. Even the throwing of an exception does not affect the reliability of resGuard3 (line 5). The destructor is called at the end of the try block (line 6).

    The screenshot shows the lifetimes of the objects.

    raii

    It’s pretty easy to apply the RAII Idiom to make out the ResourceGuard a LockGuard:

    class LockGuard{
      private:
        static inline std::mutex m;
      public:
        LockGuard() {
            m.lock();
        }
        ~LockGuard() {
            m.unlock();
        }
    };
    

     

    All instances of LockGuard share the same mutex m. When an instance goes out of scope, it automatically unlocks its mutex m.

    I wrote that the RAII Idiom is the most crucial idiom in C++. Let me name a few prominent examples.

    Applications of RAII

    • Containers of the STL, including std::string: they automatically allocate in the constructor and deallocate in their destructor
    • Smart Pointers: std::unqiue_ptr and std::shared_ptr take ownership of the underlying raw pointer; they delete the underlying raw pointer if it is not needed anymore.
    • Locks: std::lock_guard, std::unique_lock, std::shared_lock, and std::scoped_lock lock in their constructor the underlying mutex and unlock it in their destructor automatically
    • std::jthread: std::jthread in C++20 is an improved std::thread from C++11; std::jthread automatically joins in its destructor if necessary

    What’s Next?

    In my next post, I will continue my journey through the patterns of the book “Design Patterns: Elements of Reusable Object-Oriented Software”. The Observer Pattern is a behavioral pattern that should be in the toolbox of each professional programmer.

     

     

    Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, moon, Philipp Lenk, Hobsbawm, and Charles-Jianye Chen.

    Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.

    My special thanks to Embarcadero
    My special thanks to PVS-Studio
    My special thanks to Tipi.build 
    My special thanks to Take Up Code
    My special thanks to SHAVEDYAKS

    Seminars

    I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

    Standard Seminars (English/German)

    Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

    • C++ – The Core Language
    • C++ – The Standard Library
    • C++ – Compact
    • C++11 and C++14
    • Concurrency with Modern C++
    • Design Pattern and Architectural Pattern with C++
    • Embedded Programming with Modern C++
    • Generic Programming (Templates) with C++
    • Clean Code with Modern C++
    • C++20

    Online Seminars (German)

    Contact Me

    Modernes C++ Mentoring,

     

     

    0 replies

    Leave a Reply

    Want to join the discussion?
    Feel free to contribute!

    Leave a Reply

    Your email address will not be published. Required fields are marked *