工厂方法模式缺点:
1.类的个数成倍增加,导致类越来越多,增加维护成本。
2.增加了系统的抽象性和理解难度。
(判断生产什么,又变成让客户端来判断了,简单工厂模式是由工厂判断)
工厂方法模式优点:
1.符合开闭原则。
简单工厂模式+“开闭原则” = 工厂方法模式
代码如下:
#include <iostream>
using namespace std;class AbstractFruit
{
public:virtual void showName() = 0;
};class Apple :public AbstractFruit
{
public:virtual void showName(){cout << "我是苹果" << endl;}
};class Banana :public AbstractFruit
{
public:virtual void showName(){cout << "我是香蕉" << endl;}
};class Pear :public AbstractFruit
{
public:virtual void showName(){cout << "我是梨子" << endl;}
};//抽象工厂
class AbstractFruitFactor
{
public:virtual AbstractFruit *CreateFruit() = 0;
};class AppleFactor : public AbstractFruitFactor
{
public:virtual AbstractFruit *CreateFruit(){return new Apple;}
};class BananaFactor : public AbstractFruitFactor
{
public:virtual AbstractFruit *CreateFruit(){return new Banana;}
};class PearFactor : public AbstractFruitFactor
{
public:virtual AbstractFruit *CreateFruit(){return new Pear;}
};void test01()
{AbstractFruitFactor *factor = nullptr;AbstractFruit *fruit = nullptr;factor = new AppleFactor;fruit = factor->CreateFruit();fruit->showName();delete fruit;delete factor;factor = new BananaFactor;fruit = factor->CreateFruit();fruit->showName();delete fruit;delete factor;factor = new PearFactor;fruit = factor->CreateFruit();fruit->showName();delete fruit;delete factor;}int main()
{test01();return 0;
}
测试结果: