1. 案例: B帮助A追求C
2. 代理模式结构
- Subject(抽象主题角色): 声明了代理主题角色和真实主题角色共同接口;
class GiveGift { public:virtual void GiveDolls() = 0;virtual void GiveFlowers() = 0;virtual void GiveChocolate() = 0; };
- RealSubject(真实主题角色):是代理主题角色所代表的真实对象,提供真正的业务操作;
class Pursuit :public GiveGift { public:// 通过 GiveGift 继承void GiveDolls() override;void GiveFlowers() override;void GiveChocolate() override; };void Pursuit::GiveDolls() {std::cout << "Pursuit送洋娃娃" << std::endl; }void Pursuit::GiveFlowers() {std::cout << "Pursuit送鲜花" << std::endl; }void Pursuit::GiveChocolate() {std::cout << "Pursuit送巧克力" << std::endl; }
- Proxy(代理主题角色): 代理主题角色通过关联关系引用真实主题角色,可以控制和操纵真实主题对象,同时还可以在调用真实主题对象操作之前或之后增加新的服务和功能;
class Proxy :public GiveGift { public:Proxy(std::shared_ptr<GiveGift> spGiveGift);// 通过 GiveGift 继承void GiveDolls() override;void GiveFlowers() override;void GiveChocolate() override;private:std::shared_ptr<GiveGift> m_spGiveGift; };Proxy::Proxy(std::shared_ptr<GiveGift> spGiveGift):m_spGiveGift(spGiveGift) { }void Proxy::GiveDolls() {m_spGiveGift->GiveDolls(); }void Proxy::GiveFlowers() {m_spGiveGift->GiveFlowers(); }void Proxy::GiveChocolate() {m_spGiveGift->GiveChocolate(); }
- 客户端
class GiveGift; class SchoolGirl { public:void SetGiveGift(std::shared_ptr<GiveGift> spGiveGift);void Request(); private:std::shared_ptr<GiveGift> m_spGiveGift; };void SchoolGirl::SetGiveGift(std::shared_ptr<GiveGift> spGiveGift) {m_spGiveGift = spGiveGift; }void SchoolGirl::Request() {m_spGiveGift->GiveChocolate();m_spGiveGift->GiveDolls();m_spGiveGift->GiveFlowers(); }
3. 用法
std::shared_ptr<Proxy> spProxy = std::make_shared<Proxy>(std::make_shared<Pursuit>());std::shared_ptr<SchoolGirl> spSchoolGirl = std::make_shared<SchoolGirl>();spSchoolGirl->SetGiveGift(spProxy);spSchoolGirl->Request();