跳转至

代理模式

智能指针模拟 C++ 中的代理模式。此外,RAII Idiom 是代理模式的 C++ 改编版。

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.

1 Proxy Pattern

1.1 Purpose

  • Provides a placeholder for accessing another object.

1.2 Also Known As

  • Surrogate

1.3 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)

1.4 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

1.5 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 functiongetValue of MyInt. It makes no difference if you call the member function getValue on the std::unique_ptr, (line 1) on thestd::shared_ptr, (line 2), or on the object directly. All calls return the same value: proxy

1.6 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.

  • TheAdaptor Pattern adjusts an existing interface, but the Facade creates a new simplified interface.
  • TheDecorator 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.

1.8 Pros and Cons

1.8.1 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.

1.8.2 Cons

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

2 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.

2.1 Applications of RAII

  • Containers of the STL, includingstd::string: they automatically allocate in the constructor and deallocate in their destructor
  • Smart Pointers: std::unqiue_ptr andstd::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_locklock 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