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

本文详细介绍了代理模式的概念及其在C++编程中的应用场景,包括远程代理、虚拟代理、安全代理和智能引用等,通过具体代码实现展示了如何在实际项目中应用代理模式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代理模式(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,也就是Summer
	daili.GiveChocolates();
	daili.GiveDolls();
	daili.GiveFlowers();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值