标签:nan main actor 模式 des 指定 nbsp 子类 delete
工厂方法模式
让一个具体的类对应一个工厂。然后把所有工厂进行抽象。通过抽象工厂实现具体的工厂来创建对象。如果需要新增一个类,那么就需要创建一个工厂类来创建对象
优点:
1. 符合开闭原则。是简单工厂改进
2. 实现创建和使用分离
缺点:
1. 类的个数庞大。增加一个具体对象类就需要增加一个对应工厂类。增加维护成本
参考代码:
class Fruit { public: virtual void showName() = 0; }; class Apple : public Fruit { public: virtual void showName() { cout << "I am apple." << endl; } }; class Banana : public Fruit { public: virtual void showName() { cout << "I am banana." << endl; } }; class Pear : public Fruit { public: virtual void showName() { cout << "I am pear." << endl; } }; class FactoryMethod { public: virtual Fruit* createFruit() = 0; }; class AppleFactory : public FactoryMethod { public: virtual Fruit* createFruit() { return new Apple(); } }; class BananaFactory : public FactoryMethod { public: virtual Fruit* createFruit() { return new Banana(); } }; class PearFactory : public FactoryMethod { public: virtual Fruit* createFruit() { return new Pear(); } }; int main() { FactoryMethod* factory = new AppleFactory(); Fruit* apple = factory->createFruit(); apple->showName(); delete factory; delete apple; return 0; }
适用场景
1. 客户端不知道它锁需要对象的类
2. 抽象工厂类通过其子类来指定创建哪个对象
标签:nan main actor 模式 des 指定 nbsp 子类 delete
原文地址:https://www.cnblogs.com/immjc/p/9120830.html