C++ 工厂方法2
2011-12-29 15:37
134 查看
#include <iostream> #include <map> #include <string> class DeviceBase; typedef DeviceBase* (*FactoryFunction)(); class DeviceFactory { public: static void Register(std::string name, FactoryFunction instanceFunction) { m_FactoryFunctions[name] = instanceFunction; } static DeviceBase* GetInstance(std::string name) { if (m_FactoryFunctions.count(name)) { return m_FactoryFunctions[name](); } else { return NULL; } } private: static std::map<std::string, FactoryFunction> m_FactoryFunctions; }; std::map<std::string, FactoryFunction> DeviceFactory::m_FactoryFunctions; class DeviceBase { public: virtual void Draw() = 0; }; class Circle : public DeviceBase { public: void Draw() { std::cout << "Drawing a Circle......Done" << std::endl; } static DeviceBase* CreateInstance() { return new Circle; } }; class Triangle : public DeviceBase { public: void Draw() { std::cout << "Drawing a Triangle......Done" << std::endl; } static DeviceBase* CreateInstance() { return new Triangle; } }; // 工厂模式中的单例模式 class TSingleton : public DeviceBase { public: void Draw() { std::cout << "Test Singleton......Done" << std::endl; } static DeviceBase* CreateInstance() { static TSingleton* _instance = new TSingleton; return _instance; } }; int main() { DeviceFactory::Register("circle", &Circle::CreateInstance); DeviceFactory::Register("triangle", &Triangle::CreateInstance); DeviceFactory::Register("singleton", &TSingleton::CreateInstance); DeviceBase* pShape = NULL; pShape = DeviceFactory::GetInstance("singleton"); if (NULL == pShape) { std::cout << "Can't find the produce in the factory!" << std::endl; } else { pShape->Draw(); delete pShape; pShape = NULL; } return 0; }
相关文章推荐
- 设计模式:抽象工厂模式(C++)【工厂方法升级】
- C++设计模式之工厂方法模式
- 抽象工厂方法C++实现
- C++设计模式——工厂方法及工厂方法的隐藏实现(qq空间背景的例子)
- C++模板实现的通用工厂方法模式
- C++设计模式之工厂方法模式
- C++设计模式之三:Factory Method(工厂方法)
- 【C++ Design Pattern-Creational】Factory Method(工厂方法)
- C++设计模式-工厂方法
- 设计模式 - 工厂方法(Factory Method) C++实现
- QML 与 C++ 交互之工厂方法
- C++设计模式-工厂方法
- c++ 设计模式8 (Factory Method 工厂方法)
- 学雷锋之工厂方法模式学习笔记[C++版]
- 23种设计模式C++实例之工厂方法模式
- C++工厂方法与反射的简单实现
- C++设计模式————(工厂方法)
- C++入门(15):从函数或方法返回内存:工厂函数
- QML 与 C++ 交互之工厂方法
- C++模板实现的通用工厂方法模式