网站建议:179001057@qq.com

Bridge

技术2022-05-12  2

#include "stdafx.h" #include <iostream> #include <boost/shared_ptr.hpp> using namespace std; using namespace boost; /** * @brief Bridge模式对抽象接口与它的(可能是多个)实现部分进行桥接 在设计之初就该明白,一个抽象将有多少个实现部分,并且抽象和实现两者是独立演化的。 */ /** @brief Imp基类、相当于Implementor类 */ class CoffeeImp { public: CoffeeImp(void){}; virtual ~CoffeeImp(void){}; virtual void PourCoffeeImp() = 0; // 是否加奶 }; class CoffeeImp_Milk : public CoffeeImp { public: CoffeeImp_Milk(void){}; virtual ~CoffeeImp_Milk(void){}; virtual void PourCoffeeImp() { cout << "加了美味的牛奶!" << endl; } }; class CoffeeImp_Fragrant : public CoffeeImp { public: CoffeeImp_Fragrant(void){}; virtual ~CoffeeImp_Fragrant(void){}; virtual void PourCoffeeImp() { cout << "什么都没加,清香牛奶!" << endl; } }; /** @brief 咖啡类、相当于Abstraction类、维护一个CoffeeImp指针*/ class Coffee { public: Coffee(void){}; virtual ~Coffee(void){}; void SetCoffeeImp(shared_ptr<CoffeeImp> pCoffeeImp) { this->m_pCoffeeImp = pCoffeeImp; } shared_ptr<CoffeeImp> GetCoffeeImp() { return this->m_pCoffeeImp; } virtual void pourCoffee() = 0; private: shared_ptr<CoffeeImp> m_pCoffeeImp; }; class CoffeeMedium : public Coffee { public: CoffeeMedium(void){}; virtual ~CoffeeMedium(void){}; virtual void pourCoffee() { cout << "中杯"; shared_ptr<CoffeeImp> pCoffeeImp = this->GetCoffeeImp(); pCoffeeImp->PourCoffeeImp(); } }; class CoffeeSuperSize : public Coffee { public: CoffeeSuperSize(void){}; virtual ~CoffeeSuperSize(void){}; virtual void pourCoffee() { cout << "大杯"; shared_ptr<CoffeeImp> pCoffeeImp = this->GetCoffeeImp(); pCoffeeImp->PourCoffeeImp(); } }; int _tmain(int argc, _TCHAR* argv[]) { shared_ptr<CoffeeImp> pCoffeeImp(new CoffeeImp_Milk()); shared_ptr<Coffee> pCoffee1(new CoffeeMedium()); pCoffee1->SetCoffeeImp(pCoffeeImp); pCoffee1->pourCoffee(); shared_ptr<Coffee> pCoffee2(new CoffeeSuperSize()); pCoffee2->SetCoffeeImp(pCoffeeImp); pCoffee2->pourCoffee(); system("pause"); return 0; }


最新回复(0)