本文主要介绍代理模式,顾名思义,代理模式指的是为其他对象提供一种代理以控制对这个对象的访问。
代理模式的应用:
1、远程代理,也就是为一个对象在不同的地址空间提供局部代表。这样可以隐藏一个对象存在不同地址空空间的事实。;
2、虚拟代理,是根据需要创建开销很大的对象,通过它来存放实例化需要很长时间的真实对象;
3、安全代理,用来控制真实对象访问时的权限;
4、智能指引,是指当调用真实的对象时,代理处理另外一些事。
下面是代理模式的UML图。
Subject定义了RealSubject和Proxy的共用接口,这样就在任何使用RealSubject的地方都可以使用Proxy。RealSubject类定义了Proxy所代表的真实实体。Proxy保存一个引用使得代理可以访问实体,并提供一个与Subject的接口相同的接口,这样代理就可以用来替代实体。
下面请看代理模式的demo。
//抽象虚基类
#ifndef __IGIVE_GIFT_H
#define __IGIVE_GIFT_H
class IGiveGift
{
public:
virtual ~IGiveGift() {}
virtual void GiveDolls() = 0;
virtual void GiveFlowers() = 0;
virtual void GiveChocolate() = 0;
};
#endif
//实际追求者
#ifndef __PERSUIT_H
#define __PERSUIT_H
#include "IGiveGift.h"
#include "PrettyGirl.h"
#include "stdio.h"
class Persuit: public IGiveGift
{
private:
PrettyGirl mm;
public:
Persuit( PrettyGirl girl)
{
mm = girl;
}
~Persuit() {}
virtual void GiveDolls()
{
printf("%s送你洋娃娃\n", mm.m_szGirlName);
}
virtual void GiveFlowers()
{
printf("%s送你鲜花\n", mm.m_szGirlName);
}
virtual void GiveChocolate()
{
printf("%s送你巧克力\n", mm.m_szGirlName);
}
};
#endif
//代理类,里面包含实际的追求者
#ifndef __PROXY_H
#define __PROXY_H
#include "IGiveGift.h"
#include "Persuit.h"
class Proxy : public IGiveGift
{
private:
Persuit *m_pPersuit;
public:
Proxy( PrettyGirl girl )
{
m_pPersuit = NULL;
m_pPersuit = new Persuit(girl);
}
~Proxy()
{
delete m_pPersuit;
m_pPersuit = NULL;
}
virtual void GiveDolls()
{
m_pPersuit->GiveDolls();
}
virtual void GiveFlowers()
{
m_pPersuit->GiveFlowers();
}
virtual void GiveChocolate()
{
m_pPersuit->GiveChocolate();
}
};
#endif
//漂亮mm
#ifndef __PRETTY_GIRL_H
#define __PRETTY_GIRL_H
#include <string.h>
class PrettyGirl
{
public:
PrettyGirl()
{
memset(m_szGirlName, 0, 256);
}
~PrettyGirl(){}
PrettyGirl& operator=(const PrettyGirl& other)
{
if (this == &other)
{
return *this;
}
if (strlen(other.m_szGirlName) <= 0)
{
return *this;
}
memcpy(m_szGirlName, other.m_szGirlName, 256);
return *this;
}
char m_szGirlName[256];
};
#endif
//客户端代码
#include <windows.h>
#include <tchar.h>
#include "Proxy.h"
int _tmain(int _tmain(int argc, TCHAR* argv[]))
{
PrettyGirl girl;
memcpy(girl.m_szGirlName, "yyy", 256);
Proxy *proxy = new Proxy(girl);
proxy->GiveDolls();
proxy->GiveFlowers();
proxy->GiveChocolate();
delete proxy;
proxy = NULL;
return 0;
}
运行结果如下: