C++设计模式——代理模式

代理模式:为其他对象提供一种代理以控制对这个对象的访问。这样实现了业务和核心功能分离。
C++设计模式——代理模式

角色:
Subject: 抽象角色。声明真实对象和代理对象的共同接口。
Proxy: 代理角色。代理对象与真实对象实现相同的接口,所以它能够在任何时刻都能够代理真实对象。代理角色内部包含有对真实对象的引用,所以她可以操作真实对象,同时也可以附加其他的操作,相当于对真实对象进行封装。
RealSubject: 真实角色。它代表着真实对象,是我们最终要引用的对象

#define  _CRT_SECURE_NO_WARNINGS 
#include <iostream>
#include <string>

using namespace std;

//商品
class Item
{
public:
	Item(string kind, bool fact)
	{
		this->kind = kind;
		this->fact = fact;
	}

	string getKind()
	{
		return this->kind;
	}

	bool getFact()
	{
		return this->fact;
	}

private:
	string kind;//商品的种类
	bool fact; //商品的真假
};

// 抽象的购物方式
class Shopping
{
public:
	virtual void buy(Item *it) = 0;//抽象的买东西方法
};

//韩国购物
class KoreaShopping :public Shopping
{
public:
	virtual void buy(Item *it)  {
		cout << "去韩国买了" << it->getKind()<< endl;
	}
};

//美国购物
class USAShopping :public Shopping
{
public:
	virtual void buy(Item *it)  {
		cout << "去美国买了" << it->getKind() << endl;
	}
};

//海外代理
class OverseasProxy :public Shopping
{
public:
	OverseasProxy(Shopping *shpping)
	{
		this->shopping = shpping;
	}

	virtual void buy(Item *it)  {

		//1 辨别商品的真假,
		//2 进行购买()
		//3 通过海关安检,带回祖国

		if (it->getFact() == true)
		{
			cout << "1 发现正品, 要购物" << endl;

			//用传递进来的购物方式去购物
			shopping->buy(it);


			//3 安检
			cout << "2 通过海关安检, 带回祖国" << endl;
		}
		else {
			cout << "1 发现假货,不会购买" << endl;
		}
		
	}
private:
	Shopping *shopping; //有一个购物方式
};

int main(void)
{
	//1 辨别商品的真假,
	//2 进行购买()
	//3 通过海关安检,带回祖国

	Item it1("nike鞋", true);
	Item it2("CET4证书", false);

#if 0
	// 想去韩国买一个鞋
	Shopping *koreaShopping = new KoreaShopping;
	//1  辨别商品的真伪
	if (it1.getFact() == true) {
		cout << "1 发现正品, 要购物" << endl;
		//2 去韩国买了这个商品
		koreaShopping->buy(&it1);

		//3 安检
		cout << "2 通过海关安检, 带回祖国" << endl;
	}
	else {
		cout << "3 发现假货,不会购买" << endl;
	}
#endif

	Shopping *usaShopping = new USAShopping;
	Shopping *overseaProxy = new OverseasProxy(usaShopping);

	overseaProxy->buy(&it1);

	return 0;
}

代理模式案例

#define  _CRT_SECURE_NO_WARNINGS 
#include <iostream>

using namespace std;

//抽象的美女类
class BeautyGirl
{
public:
	//1 跟男人抛媚眼
	virtual void MakeEyesWithMan() = 0;
	//2 与男人共度美好的约会
	virtual void HappyWithMan() = 0;
};

//潘金莲
class JinLian :public BeautyGirl
{
public:
	//1 跟男人抛媚眼
	virtual void MakeEyesWithMan()  {
		cout << "潘金莲抛了一个媚眼" << endl;
	}
	//2 与男人共度美好的约会
	virtual void HappyWithMan()  {
		cout << "潘金莲跟你共度约会" << endl;
	}
};

class WangPo :public BeautyGirl
{
public:
	WangPo(BeautyGirl *girl) {
		this->girl = girl;
	}

	//1 跟男人抛媚眼
	virtual void MakeEyesWithMan() {
		// ...
		girl->MakeEyesWithMan();
		//...
	}
	//2 与男人共度美好的约会
	virtual void HappyWithMan() {
		girl->MakeEyesWithMan();
	}
private:
	BeautyGirl *girl;
};

//西门大官人
int main(void)
{
	BeautyGirl *jinlian = new JinLian;
	WangPo *wangpo = new WangPo(jinlian);

	//向让潘金莲抛一个
	wangpo->MakeEyesWithMan();

	//让金莲,月个会
	wangpo->HappyWithMan();
	
	return 0;
}