简单工厂模式优点:
1.客户端和具体实现解耦
2.对于某些对象的创建过程比较复杂的情况,我们不用考虑这些。
简单工厂模式缺点:
1.简单工厂模式,增加新的功能是通过修改源代码实现,不符合开闭原则。
2.这个工厂(类)职责过重,这个工厂(类)发生问题,会影响很多使用这个工厂(类)的模块
代码如下:
#include <iostream>
using namespace std;class AbstratctFruit
{
public:virtual void showName() = 0;
};class Apple :public AbstratctFruit
{
public:virtual void showName(){cout << "我是苹果" << endl;}
};class Banana :public AbstratctFruit
{
public:virtual void showName(){cout << "我是香蕉" << endl;}
};class Pear :public AbstratctFruit
{
public:virtual void showName(){cout << "我是梨子" << endl;}
};//水果工厂
class FruitFactor
{
public:static AbstratctFruit * 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;}
};void test01()
{AbstratctFruit *fruit = FruitFactor::CreateFruit("apple");fruit->showName();delete fruit;fruit = FruitFactor::CreateFruit("banana");fruit->showName();delete fruit;fruit = FruitFactor::CreateFruit("pear");fruit->showName();delete fruit;}int main()
{test01();return 0;
}
测试结果: