设计模式-创建-Factory(工厂)模式
目的:统一对象创建接口,类的具体化延迟到子类
对象很多时,对象的创建就会很复杂 多样,
工厂模式规定了统一创建接口,提高内聚 ,解耦
定义创建对象的接口,封装了对象的创建;
使得具体化类的工作延迟到了子类中。
工厂模式有好几种形式
- 简单的静态接口函数,
class Product { public: /** * @brief create a Product */ static Product *create() { return new Product; } private: Product(){} };
2. 抽象工厂类创建1
class Product { public: Product(){} }; class Factory { public: virtual Product * create() = 0; }; class ProductFactory : public Factory { public: virtual Product *create()override { return new Product; } }; int main(int argc, char *argv[]) { Factory * factory = new ProductFactory; Product* product = factory->create(); system("pause"); return 0; } //还可以进一步 对访问权限封装
3.模板工厂类创建
class Product { public: void init(){ cout << __FUNCTION__ << endl; }; Product(){} }; template< class T> class Factory { public: Factory(){}; virtual T *create(); }; template<> class Factory<Product> { public: Factory(){}; virtual Product *create() { auto ins = new Product; ins->init(); return ins; } }; int main(int argc, char *argv[]) { auto *factory = new Factory<Product>(); factory->create(); return 0; } //也可以用模板函数创建,各自的特化版本
4.抽象工厂创建2
class Fruit { public: Fruit(){} }; class Apple :public Fruit { public: Apple(){}; }; class Peach :public Fruit { public: Peach(){}; }; class Factory { public: virtual Fruit *createApple() = 0; virtual Fruit *createPeach() = 0; }; class FruitFactory : public Factory { public: Fruit *createApple()override { return new Apple; } Fruit *createPeach()override { return new Peach; } }; int main(int argc, char *argv[]) { Factory * factory = new FruitFactory; Fruit* apple = factory->createApple(); Fruit *peach = factory->createPeach(); system("pause"); return 0; }