问个设工厂模式的有关问题
问个设工厂模式的问题
我做了一个程序,用户到了工厂模式。工厂类是这样做的:
需要什么实例,调用工厂类的函数获取。
做完了之后发现,这样每个实例都是单利的。
而我的程序中可能需要将一个类实例化好几个,不能使用单例模式。
不知道我的这个工厂类应该怎么改?
------解决方案--------------------
我做了一个程序,用户到了工厂模式。工厂类是这样做的:
- C/C++ code
m_mapInst[nSytle1] = new CStyle1; m_mapInst[nSytle2] = new CStyle2; m_mapInst[nSytle3] = new CStyle3; m_mapInst[nSytle4] = new CStyle4; m_mapInst[nSytle5] = new CStyle5;
需要什么实例,调用工厂类的函数获取。
做完了之后发现,这样每个实例都是单利的。
而我的程序中可能需要将一个类实例化好几个,不能使用单例模式。
不知道我的这个工厂类应该怎么改?
------解决方案--------------------
- C/C++ code
工厂模式是将对象的实例化延迟到子类,工厂根据类型创建子类对象 有两种方法 传参和模板 单例模式是一个类有且只有一个实例 #include <iostream> #include <string> //抽象基类定义调用接口 class Base { public: Base(){} virtual ~Base(){} //防止内存泄漏 必须为virtual virtual void print()=0; }; class Derived_1: public Base { public: void print() { std::cout<<"derived_1.print()"<<std::endl; } }; class Derived_2 : public Base { public: void print() { std::cout<<"derived_2.print()"<<std::endl; } }; //工厂模式 模板创建法 template < typename T > class Factory { public: Factory(){} Base* Create() { m_pBase = new T(); return m_pBase; } ~Factory() { delete m_pBase; } private: Base* m_pBase; }; //工厂模式 类型创建 class TypeFactory { public: TypeFactory(){} virtual ~TypeFactory() { delete m_pBase; } Base* Create(std::string type) { if( type == "Derived_1") { m_pBase = new Derived_1(); } else { m_pBase = new Derived_2(); } return m_pBase; } private: Base* m_pBase; }; //单例模式 class Singleton { public: static Singleton* Instance() { if( m_instance == 0) { m_instance = new Singleton(); } return m_instance; } void AddCount() { std::cout<<"count:"<<count<<std::endl; count++; } protected: Singleton():count(0){} //无法通过外部访问 只有Instance接口创建 private: static Singleton* m_instance; //全局唯一 int count; }; Singleton* Singleton::m_instance = 0; int main() { //模板调用方法 Factory<Derived_1> fd1; Factory<Derived_2> fd2; std::cout<<"template method:"<<std::endl; fd1.Create()->print(); fd2.Create()->print(); //类型参数 TypeFactory tf; std::cout<<"Type method:"<<std::endl; tf.Create("Derived_1")->print(); tf.Create("Derived_2")->print(); //单例模式 Singleton *pSingle = Singleton::Instance(); pSingle->AddCount(); pSingle->AddCount(); return 0; }