《大话设计模式》读书笔记(C++代码实现) 第七章:代理模式

代理模式(Proxy)

  为其他对象提供一种代理以控制对这个对象的访问。

 

  

// ProxyTest01.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;


//想要追求的姑娘
class SchoolGirl
{
public :
    string name;
};

//赠送礼物
class IGiveGift
{
public :
    virtual void GiveDolls() = 0;
    virtual void GiveFlowers() = 0;
    virtual void GiveChocolate() = 0;
};

//追求者,具体表现是送给喜欢的姑娘礼物
class Pursuit : public IGiveGift
{
private :
    SchoolGirl mm;
public :
    //Pursuit(){}
    Pursuit(SchoolGirl mm)
    {
        this->mm = mm;
    }
public :
    void GiveDolls()
    {
        cout<<mm.name<<":送你洋娃娃"<<endl;
    }
    void GiveFlowers()
    {
        cout<<mm.name<<":送你鲜花"<<endl;
    }
    void GiveChocolate()
    {
        cout<<mm.name<<":送你巧克力"<<endl;
    }
};

//代理,帮追求者来做事,表现也是送东西给姑娘,当然是代追求者送的
class Proxy : public IGiveGift
{
private :
    Pursuit *pursuit;
public :
    ~Proxy(){ delete pursuit; }
    Proxy(SchoolGirl mm)
    {
        pursuit = new Pursuit(mm);
    }
public :
    void GiveDolls()
    {
        pursuit->GiveDolls();
    }
    void GiveFlowers()
    {
        pursuit->GiveFlowers();
    }
    void GiveChocolate()
    {
        pursuit->GiveChocolate();
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    SchoolGirl mm;
    mm.name = "美女";

    //追求者亲自来追女生 
    //Pursuit p(mm);
    //p.GiveDolls();
    //p.GiveFlowers();
    //p.GiveChocolate();

    //代理来代某个人来追女生 
    Proxy proxy(mm);
    proxy.GiveDolls();
    proxy.GiveFlowers();
    proxy.GiveChocolate();

    system("pause");
    return 0;
}

posted on 2012-08-14 16:27  cv_ml_张欣男  阅读(296)  评论(0编辑  收藏  举报

导航