zoukankan      html  css  js  c++  java
  • 代理模式

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    typedef struct _ShoolGirl {
        string name;
    } ShoolGirl;
    
    /* 公共接口 */
    class GiveGift {
        virtual void GiveDolls() = 0;
        virtual void GiveFlowers() = 0;
        virtual void GiveChocolate() = 0;
    };
    
    /* 实际操作类 */
    class Pursuit: public GiveGift {
    
    public:
        ShoolGirl *m_mm;
    public:
        Pursuit(): m_mm(NULL) {}
        Pursuit(ShoolGirl *mm): m_mm(mm) {}
        void GiveDolls();
        void GiveFlowers();
        void GiveChocolate();
    
    };
    
    void Pursuit::GiveDolls() {
        cout<<m_mm->name<<" give dolls!"<<endl;
    }
    
    void Pursuit::GiveFlowers() {
        cout<<m_mm->name<<" give flowers!"<<endl;
    }
    
    void Pursuit::GiveChocolate() {
        cout<<m_mm->name<<" give chocolate!"<<endl;
    }
    
    /* 代理类 */
    class Proxy: public GiveGift {
    public:
        Pursuit *m_gg;
    public:
        Proxy(): m_gg(NULL) {}
        Proxy(ShoolGirl *mm);
        ~Proxy();
        void GiveDolls();
        void GiveFlowers();
        void GiveChocolate();
    };
    
    Proxy::Proxy(ShoolGirl *mm) {
        m_gg = new Pursuit(mm);
    }
    
    Proxy::~Proxy() {
        if (m_gg) {
            delete m_gg;
        }
    }
    
    void Proxy::GiveDolls() {
        m_gg->GiveDolls();
    }
    
    void Proxy::GiveFlowers() {
        m_gg->GiveFlowers();
    }
    
    void Proxy::GiveChocolate() {
        m_gg->GiveChocolate();
    }
    
    /* 测试 */
    void main() {
        ShoolGirl mm;
        mm.name = "Girl";
    
        Proxy proxy(&mm);
        proxy.GiveDolls();
        proxy.GiveFlowers();
        proxy.GiveChocolate();
    
        system("pause");
    }

    Tips:

    代理模式使用场景:

    1.远程代理, 为一个远程对象(不在同一地址空间,例如进程间或者网络间)提供局部代表, 这样隐藏了另外一个对象不在同一地址空间的事实。

    2.虚拟代理, 根据需要创建开销很大的对象。

    3.安全代理

    4.智能指针,参考android里的智能指针的实现。

  • 相关阅读:
    c# 方法重载
    c# propertyGrid下拉选项
    c# 枚举类型
    c# socket编程
    读书笔记之ado.net entity framework
    c# delegate的invoke和bejinInvoke的区别
    C# 读书笔记之类与结构体
    c#笔记之启动新线程
    c# listview的使用
    visual studio2013 改变匹配括号的颜色
  • 原文地址:https://www.cnblogs.com/hushpa/p/4431504.html
Copyright © 2011-2022 走看看