设计模式(六)——代理模式

让类和类进行组合,获得更大的结构。

Proxy模式又叫做代理模式,是构造型的设计模式之一,它可以为其他对象提供一种代理(Proxy)
以控制对这个对象的访问。所谓代理,是指具有与代理元(被代理的对象)具有相同的接口的类,
客户端必须通过代理与被代理的目标类交互,而代理一般在交互的过程中(交互前后),进行某些特别的处理。

subject(抽象主题角色):真实主题与代理主题的共同接口。
RealSubject(真实主题角色):定义了代理角色所代表的真实对象。
Proxy(代理主题角色):含有对真实主题角色的引用,代理角色通常在将客户端调用传递给

            真是主题对象之前或者之后执行某些操作,而不是单纯返回真实的对象

#include <iostream>
#include <string>

using namespace std;

class Item
{
public:
    Item(string kind, bool flag)
    {
        this->m_kind = kind;
        this->m_flag = flag;
    }
    string get_kind()
    {
        return this->m_kind;
    }
    bool get_flag()
    {
        return this->m_flag;
    }
private:
    string m_kind;
    bool m_flag;
};

// 抽象一种购物方式,具有购物功能
class Shopping
{
public:
    virtual void buy(Item &item) = 0;
};

// 基于抽象类,实现一种具体的购物方式
class USAShopping:public Shopping
{
public:
    virtual void buy(Item &item)
    {
        cout << "去美国买了:" << item.get_kind() << endl;
    }
};

class KoreaShopping :public Shopping
{
public:
    virtual void buy(Item &item)
    {
        cout << "去韩国买了:" << item.get_kind() << endl;
    }
};

class ProxyShopping :public Shopping
{
public:
    ProxyShopping(Shopping* shop)
    {
        if (shop != NULL) {
            this->m_shop = shop;
        }
    }
    ~ProxyShopping()
    {
        if (m_shop != NULL) {
            delete this->m_shop;
        }
    }
    virtual void buy(Item &item)
    {
        if (item.get_flag()) {
            //buy
            m_shop->buy(item);
            cout << "海关报备" << endl;
        }
        else {
            cout << "假货不能购买" << endl;
        }
        
    }
private:
    Shopping * m_shop;
};

int main()
{
    Item    t1("化妆品", true);
    Item    t2("CET4证书", false);
    Item    t3("addass运动鞋", true);

    Shopping* go_usa_shopping = new USAShopping;
    ProxyShopping ps(go_usa_shopping);
    ps.buy(t1);
    ps.buy(t2);
    ps.buy(t3);

    system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/xiangtingshen/p/10357561.html