天天看點

《大話設計模式》C++實作:07 代理模式(一)

文章目錄

        • 1、什麼是代理模式?
        • 2、代理模式的适用場景?
        • 3、怎樣使用代理模式?
        • 4、執行個體

1、什麼是代理模式?

簡而言之:代理模式就是在通路對象時,引入一定程度的間接性,因為這種間接性,可以附加多種用途。

GoF描述:

代理模式(Proxy):為其他對象提供一種代理以控制對這個對象的通路。

2、代理模式的适用場景?

1、遠端代理

為一個對象在不同的位址空間提供局部代表,這樣,可以隐藏一個對象存在于不同位址空間的事實。(具體實際應用,還不了解,期待後期學習~~)

2、虛拟代理

根據需要建立開銷很大的對象,通過他來存放執行個體化需要很長時間的真實對象,這樣可以達到性能的最優化。

3、安全代理

用來控制真實對象通路時的權限。一般用于對象應該有不同的通路權限的時候。

4、智能指引

當調用真實的對象時,代理處理另外一些事。如:當第一次引用一個持久對象時,将它裝入記憶體。

或計算真實對象的引用次數,當該對象沒有引用時,可以自動釋放它。

或通路一個實際對象前,檢查是否已經鎖定它,以確定其他對象不能改變它。

他們都是通過代理在通路一個對象時附加一些内務處理。

3、怎樣使用代理模式?

初級,boy找代理追girl

《大話設計模式》C++實作:07 代理模式(一)

4、執行個體

1、IGiveGift.h 公共接口函數

#pragma once
class IGiveGift
{
public:
	virtual void giveDools() = 0;
	virtual void giveFlowers() = 0;
	virtual void giveChocolate() = 0;
};
           

2、Pursuit.h 追求者

#pragma once
#include "SchoolGirl.h"
#include "IGiveGift.h"
#include <iostream>
#include <string>
using namespace std;

class Pursuit
	:public IGiveGift
{
public:
	Pursuit(SchoolGirl* girl);
public:
	void giveDools();
	void giveFlowers();
	void giveChocolate();
private:
	SchoolGirl* mm;
};

Pursuit::Pursuit(SchoolGirl* girl)
	:mm(girl)
{

}

void Pursuit::giveDools()
{
	cout << mm->getName() << ",送你手辦" << endl;
}

void Pursuit::giveFlowers()
{
	cout << mm->getName() << ",送你花花" << endl;
}

void Pursuit::giveChocolate()
{
	cout << mm->getName() << ",送你糖糖" << endl;

}


           

3、Proxy.h 代理

#pragma once
#include "SchoolGirl.h"
#include "IGiveGift.h"
#include "Pursuit.h"
#include <iostream>
using namespace std;

class Proxy
	:public IGiveGift
{
public:
	Proxy(SchoolGirl* girl);
public:
	void giveDools();
	void giveFlowers();
	void giveChocolate();
private:
	Pursuit* boy;
};

Proxy::Proxy(SchoolGirl* girl)
{
	boy = new Pursuit(girl);//這裡是實作代理的重要地方1
}

void Proxy::giveDools()
{
	boy->giveDools();//這裡是實作代理的重要地方2
}

void Proxy::giveFlowers()
{
	boy->giveFlowers();
}

void Proxy::giveChocolate()
{
	boy->giveChocolate();
}
           

4、SchoolGirl.h 被追求者

#pragma once
#include<iostream>
#include<string>
using namespace std;
class SchoolGirl
{
public:
	string getName() { return name; }
	void setName(const string& _name) {	name = _name;}
private:
	string name;
};


           

5、測試

#include "Proxy.h"
#include "Pursuit.h"
#include "SchoolGirl.h"

void test()
{
	SchoolGirl* girl = new SchoolGirl();
	girl->setName("墨白");
	Proxy* p1 = new Proxy(girl);
	p1->giveDools();
	p1->giveFlowers();
	p1->giveChocolate();
}

int main()
{
	test();
	system("pause");
	return 0;
}
           
《大話設計模式》C++實作:07 代理模式(一)

更新版:《大話設計模式》C++實作:07 代理模式(二)

此為《大話設計模式》學習心得系列 P58~~

繼續閱讀