工厂方法模式 = 简单工厂模式 + 开闭原则

类的个数成倍增多,维护成本很高

适用场景:

  • 客户端不知道它所需要的对象的类
  • 抽象工厂类通过其子类来指定创建哪个对象

工厂方法模式

// 工厂方法模式
class AbstractFruit{
public:
    virtual void showName() = 0;
};
class Apple : public AbstractFruit{
public:
    void showName() override{
        cout << "我是苹果!" << endl;
    }
};
class Banana : public AbstractFruit{
public:
    void showName() override{
        cout << "我是香蕉!" << endl;
    }
};
class Pear : public AbstractFruit{
public:
    void showName() override{
        cout << "我是鸭梨!" << endl;
    }
};
// 抽象工厂
class AbstractFruitFactory{
public:
    virtual AbstractFruit* CreateFruit() = 0;
};
class AppleFactory : public AbstractFruitFactory{
public:
    AbstractFruit* CreateFruit() override{
        return new Apple;
    }
};
class PearFactory : public AbstractFruitFactory{
public:
    AbstractFruit* CreateFruit() override{
        return new Pear;
    }
};
class BananaFactory : public AbstractFruitFactory{
public:
    AbstractFruit* CreateFruit() override{
        return new Banana;
    }
};
int main()
{
    AbstractFruitFactory* factory = nullptr;
    AbstractFruit* fruit = nullptr;
    factory = new AppleFactory;
    fruit = factory->CreateFruit();
    fruit->showName();
    delete fruit;
    delete factory;
    factory = new BananaFactory;
    fruit = factory->CreateFruit();
    fruit->showName();
    delete fruit;
    delete factory;
    factory = new PearFactory;
    fruit = factory->CreateFruit();
    fruit->showName();
    delete fruit;
    delete factory;
    return 0;
}