本文主要介紹代理模式,顧名思義,代理模式指的是爲其他對象提供一種代理以控制對這個對象的訪問。
代理模式的應用:
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;
}
運行結果如下: