首页 > 代码库 > 代理模式

代理模式

代理模式:为其他对象提供一种代理以控制对这个对象的访问.

Pursuit 通过 Proxy 送给SchoolGirl 礼物.

 

#pragma once
class IGiveGift
{
public:
    virtual void GiveDolls()=0;
    virtual void GiveFlowers()=0;
    virtual void GiveChocolate()=0;
};

 

#pragma once
#include "igivegift.h"
#include "SchoolGirl.h"
#include "Pursuit.h"
class Proxy :
    public IGiveGift
{
public:
    Proxy(SchoolGirl mm)
    {
        GG = new Pursuit(mm);
    }
    ~Proxy(void);
    virtual void GiveDolls()
    {
        GG->GiveDolls();
    }
    virtual void GiveFlowers()
    {
        GG->GiveFlowers();
    }
    virtual void GiveChocolate()
    {
        GG->GiveChocolate();
    }
private:
    Pursuit *GG;
};

 

#pragma once
#include "Igivegift.h"
#include "SchoolGirl.h"
#include <iostream>
class Pursuit :
    public IGiveGift
{
public:
    Pursuit(SchoolGirl mn):mm(mn){}
    ~Pursuit(void);
    virtual void GiveDolls()
    {
        cout<<mm.getName()<<":送你洋娃娃"<<endl;
    }
    virtual void GiveFlowers()
    {
        cout<<mm.getName()<<":送你花朵"<<endl;
    }
    virtual void GiveChocolate()
    {
        cout<<mm.getName()<<":送你巧克力"<<endl;
    }
private:
    SchoolGirl mm;
};

 

#pragma once
#include <string>
using namespace std;
class SchoolGirl
{
public:
    SchoolGirl(string na):name(na){}
    string getName()
    {
        return name;
    }
    ~SchoolGirl(void);
private:
    string name;
};

 

main方法

#include "stdafx.h"
#include "Proxy.h"
#include "SchoolGirl.h"


int _tmain(int argc, _TCHAR* argv[])
{
    SchoolGirl girl("孙晓红");
    Proxy daili(girl);
    daili.GiveChocolate();
    daili.GiveDolls();
    daili.GiveFlowers();
    return 0;
}