您的位置:首页 > 编程语言 > C语言/C++

设计模式之代理模式(C++实现)

2016-05-24 16:59 543 查看
代理模式:为其他对象提供代理以控制对这个对象的访问。

代理模式运用的场合:

1、远程代理。也就是为对象在不同的地址空间提供局部变量代表,这样可以隐藏一个对象存在于不同地址空间的事实

2、虚拟代理。根据需要创建开销很大的对象。通过它来存放实例化需要很长时间的真实对象。

3、安全代理。用来控制真实对象访问时的权限。

4、智能指引。指当调用真实对象时,代理处理另外一些事。

例如下例,真实对象Pursuit要给蠢蠢送礼物,但他不认识蠢蠢,只能通过代理Proxy来送礼物

/******************************************************************main.cpp************************************************************/

#include "Proxy.h"

int main()
{
Proxy * proxy = new Proxy("蠢蠢");
proxy->GiveChocolate();
proxy->GiveDolls();
proxy->GiveFlowers();
getchar();
return 0;
}


/******************************************************************Givegift.h************************************************************/

#include <iostream>
#include <string>
#pragma once
using namespace std;
class Givegift
{
public:
virtual void  GiveChocolate()=0;
virtual void  GiveDolls()=0;
virtual void  GiveFlowers()=0;
};


/******************************************************************Pursuit.h************************************************************/

#include "Givegift.h"

class Pursuit:public Givegift
{
string girlname;
public:
Pursuit(string name)
{
girlname = name;
}
void virtual GiveChocolate()
{
cout<<"给"<<girlname<<"巧克力"<<endl;
};
void virtual GiveDolls()
{
cout<<"给"<<girlname<<"玩具"<<endl;
};
void virtual GiveFlowers()
{
cout<<"给"<<girlname<<"花"<<endl;
};
};


/******************************************************************Proxy.h************************************************************/

#include "Givegift.h"
#include "Pursuit.h"

class Proxy:public Givegift
{
Pursuit *myPursuit;
public:
Proxy(string name)
{
myPursuit = new Pursuit(name);
}
void GiveChocolate()
{
myPursuit->GiveChocolate();
};
void GiveDolls()
{
myPursuit->GiveDolls();
};
void GiveFlowers()
{
myPursuit->GiveFlowers();
};
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: