[C++]代理模式

代理模式给某一个对象提供一个代理对象,并由代理对象控制对原对象的引用。通俗的来讲代理模式就是我们生活中常见的中介。

C++代码如下:

// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

// 参考大话设计模式 - 代理模式

#include <iostream>

using namespace std;

#ifndef SAFE_DELETE
#define SAFE_DELETE(p) { if(p){delete(p); (p)=NULL;} }
#endif


// 代理模式
// 抽象类,包含功能接口
// 实现类,继承抽象类,并实现功能
// 代理类,集成抽象类,定义实现类的成员变量,通过实现类的对象,来调用具体实现功能的函数


// 该类仅为满足用例,可不存在
class SchoolGirl
{
public:
	void setname(string name) {
		name_ = name;
	}

	string getname() {
		return name_;
	}

private:
	string name_;
};

// 礼物接口
class CGiveGift
{
public:
	virtual void GiveDolls() = 0;
	virtual void GiveFollows() = 0;
	virtual void GiveChocolates() = 0;
};

// 追求者类,具体实现了礼物接口
class Pursuit : public CGiveGift {
public:
	Pursuit(SchoolGirl* schoolgirl) {
		schoolgirl_ = schoolgirl;
	}

	void GiveDolls() {
		if (schoolgirl_) {
			cout << "pursuit give dolls to " << schoolgirl_->getname() << "\n";
		}
	}

	void GiveFollows() {
		if (schoolgirl_) {
			cout << "pursuit give follows to " << schoolgirl_->getname() << "\n";
		}
	}

	void GiveChocolates() {
		if (schoolgirl_) {
			cout << "pursuit give chocolates to " << schoolgirl_->getname() << "\n";
		}
	}

private:
	SchoolGirl* schoolgirl_ = nullptr;
};

// 代理类,内部定义具体实现类的对象,在继承的函数中调用
class Proxy : public CGiveGift {
public:
	Proxy(SchoolGirl* schoolgirl) {
		pursuit_ = new Pursuit(schoolgirl);
	}

	~Proxy() {
		SAFE_DELETE(pursuit_);
	}
	
	void GiveDolls() {
		if (pursuit_) {
			pursuit_->GiveDolls();
		}
	}

	void GiveFollows() {
		if (pursuit_) {
			pursuit_->GiveFollows();
		}
	}

	void GiveChocolates() {
		if (pursuit_) {
			pursuit_->GiveChocolates();
		}
	}


private:
	Pursuit* pursuit_ = nullptr;
};


int main()
{
	SchoolGirl* schoolgirl = new SchoolGirl();
	schoolgirl->setname("李娇娇");

	// 代理对象
	Proxy* proxy = new Proxy(schoolgirl);
	// 代理对象中调用具体实现类的对象的实现方法
	proxy->GiveDolls();
	proxy->GiveFollows();
	proxy->GiveChocolates();

	SAFE_DELETE(proxy)
	SAFE_DELETE(schoolgirl)

	return 0;
}


github源码路径:https://github.com/dangwei-90/Design-Mode

持续更新中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值