设计模式--访问器模式

  • 代理模式解决的场景是:当不希望客户端直接访问实体类,或者希望给实体类的方法加上一些特定的附加操作时,通过一个代理类,不让客户端直接访问实体类,而是通过代理类。代理类和实体拥有一样的接口,此外代理保存着实体类的实例。

    demo实现如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    #include <iostream>

    class Runnable {
    public:
    virtual void Run() = 0;
    };

    class Dog : public Runnable {
    public:
    virtual void Run() override {
    std::cout << "Dog run\n";
    }
    };

    class Cat : public Runnable {
    public:
    virtual void Run() override {
    std::cout << "Cat run\n";
    }
    };

    class Proxy : public Runnable {
    public:
    Proxy(Runnable* runnable) :runnable_(runnable) {}
    void Set(Runnable* runnable) { runnable_ = runnable; }
    virtual void Run() override {
    /* do something before running*/
    runnable_->Run();
    /* do something after running*/
    }
    private:
    Runnable* runnable_;
    };

    int main() {
    Dog dog;
    Cat cat;
    Proxy proxy(&dog);
    proxy.Run();
    proxy.Set(&cat);
    proxy.Run();
    return 0;
    }