大话设计模式C++版本-04-代理模式

概念

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

使用场景

  1. 想在访问一个类时做一些控制;
  2. 直接访问对象时会带来的问题,比如说:要访问的对象在远程的机器上。

一般步骤

  1. 被代理者代理者的共同行为抽象出来作为一个类;
    class GiveGift // 送礼物类
    {
    public:
    	virtual	void GiveDolls() = 0;
    	virtual	void GiveFlowers() = 0;
    	virtual	void GiveChocolate() = 0;
    };
    
  2. 被代理者的类;
    class Pursuit : public GiveGift // 被代理者-追求者类
    {
    public:
    	Pursuit(SchoolGirl *mm)
    	{
    		this->mm = mm;
    	}
    	void GiveDolls()
    	{
    		cout << mm->name << "送你洋娃娃" << endl;
    	}
    	void GiveFlowers()
    	{
    		cout << mm->name << "送你鲜花" << endl;
    	}
    	void GiveChocolate()
    	{
    		cout << mm->name << "送你巧克力" << endl;
    	}
    private:
    	SchoolGirl *mm; 
    };
    
  3. 代理者类,里面的行为全部调用被代理者的行为;
    class Proxy : public GiveGift // 代理类
    {
    public:
    	Proxy(SchoolGirl *mm)
    	{
    		gg = new Pursuit(mm);
    	}
    	void GiveDolls()
    	{
    		gg->GiveDolls();
    	}
    	void GiveFlowers()
    	{
    		gg->GiveFlowers();
    	}
    	void GiveChocolate()
    	{
    		gg->GiveChocolate();
    	}
    private:
    	Pursuit	*gg; // 被代理者
    };
    

具体实例

// 04Proxy.cpp
#include <iostream>
#include <string>

using namespace std;

class SchoolGirl // 女孩类
{
public:
	SchoolGirl(string name)
	{
		this->name = name;
	}
	string name;
};

class GiveGift // 送礼物类
{
public:
	virtual	void GiveDolls() = 0;
	virtual	void GiveFlowers() = 0;
	virtual	void GiveChocolate() = 0;
};

class Pursuit : public GiveGift // 被代理者-追求者类
{
public:
	Pursuit(SchoolGirl *mm)
	{
		this->mm = mm;
	}
	void GiveDolls()
	{
		cout << mm->name << "送你洋娃娃" << endl;
	}
	void GiveFlowers()
	{
		cout << mm->name << "送你鲜花" << endl;
	}
	void GiveChocolate()
	{
		cout << mm->name << "送你巧克力" << endl;
	}
private:
	SchoolGirl *mm; 
};

class Proxy : public GiveGift // 代理类
{
public:
	Proxy(SchoolGirl *mm)
	{
		gg = new Pursuit(mm);
	}
	void GiveDolls()
	{
		gg->GiveDolls();
	}
	void GiveFlowers()
	{
		gg->GiveFlowers();
	}
	void GiveChocolate()
	{
		gg->GiveChocolate();
	}
private:
	Pursuit	*gg; // 被代理者
};

int main()
{
	SchoolGirl *jiaojiao = new SchoolGirl("李娇娇");
	
	Proxy *DaiLi = new Proxy(jiaojiao);
	
	DaiLi->GiveDolls();
	DaiLi->GiveFlowers();
	DaiLi->GiveChocolate();
	
	return 0;
}

参考资料

《大话设计模式》

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章