1. 实现了客户端与功能类的解耦
  2. 但是违反了类的单一职责原则,整个类的代码冗长,阅读难度、维护难度和测试难度也很大
  3. 违反了开闭原则,增添功能要修改源代码

适用场景:

  • 工厂类负责创建的对象比较少,不会造成工厂方法中的业务逻辑太过复杂
  • 客户端只知道传入工厂类的参数,对于如何创建对象并不关心

简单工厂模式

// 简单工厂模式
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 FruitFactory{
public:
    static AbstractFruit* CreateFruit(string flag){
        if(flag == "apple"){
            return new Apple;
        }
        else if(flag == "banana"){
            return new Banana;
        }
        else if(flag == "pear"){
            return new Pear;
        }
        else{
            return nullptr;
        }
    }
};
int main()
{
    AbstractFruit* fruit = FruitFactory::CreateFruit("apple");
    fruit->showName();
    delete fruit;
    fruit = FruitFactory::CreateFruit("banana");
    fruit->showName();
    delete fruit;
    fruit = FruitFactory::CreateFruit("pear");
    fruit->showName();
    delete fruit;
    return 0;
}