您的位置:首页 > 其它

设计模式:7 代理模式

2015-08-12 01:53 302 查看
代理模式:为其他对象提供一种代理以控制对这个对象的访问

Subject类:定义了RealSubject和Proxy的共用接口,这样就在任何使用RealSubject的地方使用Proxy



代理模式应用:

1远程代理:为一个对象在不同的地址空间提供局部代表,隐藏一个对象存在于不同地址空间的事实



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



3安全代理:控制真是对象访问时的权限



4智能指引:当调用真实的对象时,代理处理另外一些事实。[智能指针]



main.cpp

#include <iostream>
#include <stdlib.h>
#include "SchoolGirl.h"
#include "Proxy.h"

using namespace std;

void process()
{
	SchoolGirl panyin("潘颖");
	Proxy agent(panyin);
	agent.giveChocolate();
	agent.giveDolls();
	agent.giveFlower();
}

int main(int argc,char* argv[])
{
	process();
	system("pause");
	return 0;
}



SchoolGirl.h

#ifndef SCHOOLGIRL_H
#define SCHOOLGIRL_H

#include <string>

class SchoolGirl
{
public:
	SchoolGirl(const std::string& sName);
	~SchoolGirl(void);
	std::string getName();
public:
	std::string _sName;
};

#endif


SchoolGirl.cpp

#include "SchoolGirl.h"

SchoolGirl::SchoolGirl(const std::string& sName):_sName(sName)
{
}

SchoolGirl::~SchoolGirl(void)
{
}

std::string SchoolGirl::getName()
{
	return _sName;
}


Proxy.h

#ifndef PROXY_H
#define PROXY_H
#include "givegift.h"
#include "Pursuit.h"
#include "SchoolGirl.h"
#include <memory>
class Proxy :
	public GiveGift
{
public:
	Proxy(SchoolGirl& mm);
	~Proxy(void);
	void giveFlower();
	void giveChocolate();
	void giveDolls();
private:
	std::shared_ptr<Pursuit> _ptrPursuit;//关键:代理模式聚合了真正的主类去,在代理中的方法全部源自真正主类的方法
};

#endif




Proxy.cpp

#include "Proxy.h"

Proxy::Proxy(SchoolGirl& mm)
{
	_ptrPursuit.reset(new Pursuit(mm));
}

Proxy::~Proxy(void)
{
}

void Proxy::giveFlower()
{
	_ptrPursuit->giveFlower();
}

void Proxy::giveChocolate()
{
	_ptrPursuit->giveChocolate();
}

void Proxy::giveDolls()
{
	_ptrPursuit->giveDolls();
}


GiveGift.h

#ifndef GIVEGIFT_H
#define GIVEGIFT_H
//主类
class GiveGift
{
public:
	GiveGift(void);
	virtual ~GiveGift(void);
	virtual void giveFlower();
	virtual void giveChocolate();
	virtual void giveDolls();

};
#endif


GiveGift.cpp

#include "GiveGift.h"

GiveGift::GiveGift(void)
{
}

GiveGift::~GiveGift(void)
{
}

void GiveGift::giveFlower()
{
}

void GiveGift::giveChocolate()
{
}

void GiveGift::giveDolls()
{
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: