The Proxy Pattern

Contents[Show]

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

 

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.

  • 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

 

Rainer D 6 P2 540x540Modernes C++ Mentoring

Stay informed about my mentoring programs. Subscribe for the news.

 

 

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, Marko, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, 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, Evangelos Denaxas, 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, Matthieu Bolt, 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, and Phillip Diekmann.

 

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

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

My special thanks to PVS-Studio PVC Logo

 

Seminars

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

Bookable (Online)

German

Standard Seminars (English/German)

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

New

Contact Me

Modernes C++,

RainerGrimmDunkelBlauSmall

 

Mentoring

Stay Informed about my Mentoring

 

English Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Interactive Course: The All-in-One Guide to C++20

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 319

Yesterday 6417

Week 13220

Month 33967

All 10955428

Currently are 199 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments