1.说明
请参阅第一篇文章
2.代理模式简介
代理模式:为其它对象提供一种代理,以控制对这个对象的访问。
代理者和被申请代理的对象二者应该有相同的接口,或者是申请代理者的接口是代理者接口的子集,因为可以代理多个对象。
代理的模式有:
远程代理:为一个对象在不同的地址空间提供局部代表。这样可以隐藏一个对象存在于不同地址空间的事实。
虚拟代理:根据需要创建开销很大的对象,通过他来存放实例化需要很长时间的真是对象。
安全代理:用来控制真是对象访问时的权限。
智能引用:当调用真实对象时,代理处理另外一些事
代理模式就是在访问对象时引入了一定程度的间接性,因为这种间接性,可以附加多种用途
3.UML
4.代码
背景说明:
某某喜欢一女孩,让代理者给女孩送礼物等方法包括:送礼,送花等,在每次操作后,女孩能够把状态通过代理者告诉给某某,是一个双向逻辑,比上图略为复杂【模拟实际中环境,并没有让女孩直接告诉某某这种模式】,至于信息回传可能在软件开发中会很少用到。
//ProxyBase.h 抽象代理接口封装
#ifndef __PROXYBASE_H
#define __PROXYBASE_H
#include <iostream>
#include <string>
#include "Girl.h"
class CProxyBase
{
public:
//接口
CProxyBase(){}
virtual void give_gift() = 0;
virtual void give_flower() = 0;
virtual void give_care() = 0;
virtual void rely_info(std::string info) = 0;
//需要处理的实例(接收实例反馈,并传给client)
virtual CGirl* get_girl()
{
}
};
#endif
//代理者实现,Proxy.h
#ifndef __PROXY_H
#define __PROXY_H
#include "Girl.h"
#include "ProxyBase.h"
//代理:用我的资源(线程资源)去调用别人的方法,而不是自己方法
class CProxy:public CProxyBase
{
public:
//添加客户信息
void set_myclient(CProxyBase* client)
{
m_client = client;
m_girl = m_client->get_girl();
}
//反馈信息回传给客户
void rely_info(std::string info)
{
m_client->rely_info(info);
}
//接口实例
void give_gift()
{
m_client->give_gift();
rely_info(m_girl->rely());
}
void give_flower()
{
m_client->give_flower();
rely_info(m_girl->rely());
}
void give_care()
{
m_client->give_care();
rely_info(m_girl->rely());
}
private:
CGirl* m_girl;
CProxyBase* m_client;
};
#endif
//请求的代理者,RealSub.h
#ifndef __REALSUB_H
#define __REALSUB_H
#include "ProxyBase.h"
#include "Girl.h"
class CRealSub:public CProxyBase
{
public:
CRealSub(std::string name):m_name(name)
{
}
void give_gift()
{
std::cout<<"Hi "<< m_girl->getname()<<" give your gift from"<< m_name<<std::endl;
}
void give_care()
{
std::cout<<"Be care "<<m_girl->getname()<<" from"<<m_name<<std::endl;
}
void give_flower()
{
std::cout<<"This is your flower "<<m_girl->getname()<<" from"<<m_name<<std::endl;
}
void rely_info(std::string info)
{
std::cout<<info.c_str()<<std::endl;
}
public:
CGirl* get_girl()
{
CGirl* girl = NULL;
if (m_girl != NULL)
girl = m_girl;
return girl;
}
void set_girl(CGirl* girl)
{
if (girl != NULL)
m_girl = girl;
}
private:
std::string m_name;
CGirl* m_girl;
};
#endif
//客户端调用
#include <iostream>
#include "RealySub.h"
#include "Girl.h"
#include "ProxyBase.h"
#include "Proxy.h"
int main(void)
{
CGirl* girl = new CGirl("jiaojiao");
CRealSub* sub = new CRealSub("xiaozi");
sub->set_girl(girl);
CProxy* proxy = new CProxy;
proxy->set_myclient(sub);
proxy->give_gift();
proxy->give_care();
proxy->give_flower();
return 0;
}