设计模式C++实现四:代理模式

来源:互联网 发布:农村淘宝快递加盟 编辑:程序博客网 时间:2024/04/28 22:59

代理模式(Proxy):为其他对象提供一种代理以控制对这个对象的访问。

应用场景:1.远程代理,也就是为一个对象在不同的地址空间提供局部代表,这样就可以隐藏一个对象存在于不同地址空间的事实。

    2.虚拟代理,是根据需要创建开销很大的对象。通过它来存放实例化需要很长时间的真实对象。例如一个很大的HTML网页的打开,我们看到图片是一张一张下载后才能看到,而未打开的图片框,就是通过虚拟代理来替代真实的图片,此时代理存储了真实图片的路径和尺寸。

   3.安全代理,用来控制真实对象访问时的权限。

   4.智能引用,是指当调用真实的对象是,代理处理另外一些事。


#ifndef PROXY_H#define PROXY_H#include<string>#include<iostream>using namespace std;class SchoolGirl{public:string name;//女孩是谁SchoolGirl(string mm) :name(mm){}};class IGiveGift{public:virtual void GiveDolls() const= 0;virtual void GiveFlowers() const= 0;virtual void GiveChocolates()const = 0;};class Pursuit :public IGiveGift{SchoolGirl mm;//追求谁public:Pursuit(SchoolGirl m) :mm(m){}void GiveDolls() const ;void GiveFlowers() const;void GiveChocolates()const;};class Proxy :IGiveGift{Pursuit gg;//为谁代理public:Proxy(SchoolGirl m) :gg( Pursuit(m)){}void GiveDolls() const{gg.GiveDolls();}void GiveFlowers() const{gg.GiveFlowers();}void GiveChocolates()const{gg.GiveChocolates();}};void Pursuit::GiveDolls() const{cout << mm.name << " give your dolls.\n";}void Pursuit::GiveFlowers() const{cout << mm.name << " give your flowers.\n";}void Pursuit::GiveChocolates()const{cout << mm.name << " give your chocolates.\n";}#endif

#include"Proxy.h"int main(){SchoolGirl m("Summer");Proxy daili(m);//此处代理的操作表明是由daili执行的,而在代理内部是由Pursuit gg 发起的,//也就是那些花,娃娃,巧克力都是gg的,只是由daili转交给m,也就是Summerdaili.GiveChocolates();daili.GiveDolls();daili.GiveFlowers();return 0;}


0 0