代理(Proxy)模式,爲其它對象提供一種代理以控制對這個對象的訪問。在某些狀況下一個對象不適合或者不能直接引用另外一個對象,而代理對象能夠在客戶端和目標對象之間起到中介做用。ios
Subject類,定義了RealSubject和Proxy的公共接口,這樣就在任何使用RealSubject的地方均可以使用Proxy。設計模式
RealSubject類,定義了Proxy所表明的的真實實體。安全
Proxy類,保存一個引用使得代理能夠訪問實體,並提供一個與Subject的接口相同的接口,這樣代理就能夠用來代替實體。ide
Client,經過Proxy類間接的和RealSubject進行通訊。學習
優勢:ui
1.在客戶端和目標對象之間起到一箇中介的做用,這樣能夠對目標對象起到一個保護做用。spa
缺點:設計
1.在客戶和目標對象之間增長了一個抽象層,這可能會影響處處理速度。3d
適用場景:代理
1.遠程代理,也就是爲一個對象在不一樣的地址空間提供局部表明。這樣能夠隱藏一個對象存在於不一樣地址空間的事實。
2.虛擬代理,是根據須要建立開銷很大的對象。經過它來存放實例化須要很長時間的真實對象。
3.安全代理,用來控制真實對象的訪問權限。
4.智能指引,是指當調用真實的對象時,代理處理另一些事。例如只能指針。
學習《大話設計模式》的最後一章了,設計模式之路纔剛剛開始。依然是使用該書中A委託B追求C的例子吧。
1.Subject類
#ifndef SUBJECT_H_ #define SUBJECT_H_ //這個虛基類,是代理和真實對象所共有的方法 //這這個例子中,代理和真實對象都具備送花、送洋娃娃的能力 class Subject { public: virtual void giveDolls() = 0; virtual void giveFlowers() = 0; virtual void giveChocolate() = 0; Subject() = default; virtual ~Subject() = default; }; #endif
2.RealSubject類
#ifndef PURSUIT_H_ #define PURSUIT_H_ //這個類是真實的對象(目標類) #include "Subject.h" #include <string> #include <iostream> class Pursuit : public Subject { private: std::string m_strGirlsName; //被追求女孩的名字 public: void giveDolls() override; void giveFlowers() override; void giveChocolate() override; Pursuit(const std::string strGirlsName) : m_strGirlsName(strGirlsName){}; Pursuit() = default; ~Pursuit() = default; }; #endif #include "Pursuit.h" void Pursuit::giveDolls() { std::cout << m_strGirlsName << ".Give you Dolls." << std::endl; } void Pursuit::giveFlowers() { std::cout << m_strGirlsName << ".Give you Flowers." << std::endl; } void Pursuit::giveChocolate() { std::cout << m_strGirlsName << ".Give you Cholocate." << std::endl; }
3.Proxy類
#ifndef PROXY_H_ #define PROXY_H_ #include "Pursuit.h" class Proxy : public Subject { private: Pursuit m_Pursuit; public: void giveDolls() override; void giveFlowers() override; void giveChocolate() override; Proxy(const std::string strGirlsName) : m_Pursuit(Pursuit(strGirlsName)){}; ~Proxy() = default; }; #endif #include "Proxy.h" void Proxy::giveDolls() { m_Pursuit.giveDolls(); } void Proxy::giveFlowers() { m_Pursuit.giveFlowers(); } void Proxy::giveChocolate() { m_Pursuit.giveChocolate(); }
4.Client
#include "Proxy.h" using namespace std; int main(int argc,char *argv[]) { Proxy daili("Yang yang"); daili.giveDolls(); daili.giveFlowers(); daili.giveChocolate(); return (1); }