简介
代理模式提供了一个代理,达到控制访问对象的目的。代理模式分为远程代理,保护代理,虚拟代理,缓冲代理和智能引用代理等。
UML 类图
示例
有句广告词,没有中间商赚差价,这个中间商很多时候就是代理的角色。中间商越多就是层层代理。很多商品都有一级代理商二级代理商等。在这里我们举一个火车票代售点的故事。
代理实现,proxy.h
#ifndef PROXY_H
#define PROXY_H
#include <iostream>
using namespace std;
#define SAFE_DELETE(p) if(p){delete (p); (p) = NULL;}
class CTicketSale
{
public:
virtual void GetTicket() = 0;};
class CStationSale:public CTicketSale
{
public:
void GetTicket()
{cout<<"Get Ticket."<<endl;}
};
class CProxySale:public CTicketSale
{
public:
CProxySale()
{m_pTicketSale = new CStationSale;}
~CProxySale()
{SAFE_DELETE(m_pTicketSale);
}
void GetTicket()
{
cout<<"Enter proxy:"<<endl;
m_pTicketSale->GetTicket();}
private:
CTicketSale* m_pTicketSale;
};
#endif
客户端调用,main.cpp
#include "proxy.h"
int main(int argc, char* argv[])
{
CTicketSale* pProxySale = new CProxySale;
pProxySale->GetTicket();
SAFE_DELETE(pProxySale)
return 0;
}