#include "stdafx.h" #include <iostream> #include <boost/shared_ptr.hpp> using namespace std; /** * @brief 衣服有纽扣也有衣领,纽扣、衣领这一般需要交给加工厂单独来制作 假设在中国加工厂制作称为中国的衣服(中国制造),在美国加工厂制作称为美国的衣服(美国制造) 以下采用abstractFactory模式来演示 * @warning 衣服包括衣领、纽扣。衣服做为一个抽象工程,可以生成衣领、纽扣;两者相互关联 */ class IButton ///< 纽扣接口 { public: virtual void Button() = 0; }; class ChinaButton : public IButton { public: virtual void Button() { cout << "中国纽扣" << endl; } }; class USAButton : public IButton { public: virtual void Button() { cout << "美国纽扣" << endl; } }; class ICollar ///< 衣领接口 { public: virtual void Collar() = 0; }; class ChinaCollar : public ICollar { public: virtual void Collar() { cout << "中国衣领" << endl; } }; class USACollar : public ICollar { public: virtual void Collar() { cout << "美国衣领" << endl; } }; class IClothesFactory ///< 衣服加工厂 { public: virtual IButton* DoButton() = 0; virtual ICollar* DoCollar() = 0; }; class ChinaFactory : public IClothesFactory ///< 中国衣服加工厂 { public: virtual IButton* DoButton() { return new ChinaButton(); } virtual ICollar* DoCollar() { return new ChinaCollar(); } }; class USAFactory : public IClothesFactory { public: virtual IButton* DoButton() { return new USAButton(); } virtual ICollar* DoCollar() { return new USACollar(); } }; int _tmain(int argc, _TCHAR* argv[]) { boost::shared_ptr<ChinaFactory> pChinaFactory(new ChinaFactory); boost::shared_ptr<IButton> pButton(pChinaFactory->DoButton()); boost::shared_ptr<ICollar> pCollar(pChinaFactory->DoCollar()); pButton->Button(); pCollar->Collar(); system("pause"); return 0; }