大話設計模式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;
}

參考資料

《大話設計模式》

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