工厂方法模式之所以有一个别名叫多态性工厂模式是因为具体工厂类都有共同的接口, 或者有共同的抽象父类。 当系统扩展需要添加新的产品对象时,仅仅需要添加一个具体对象以及一个具体工厂对 象,原有工厂对象不需要进行任何修改,也不需要修改客户端,很好的符合了“开放-封闭” 原则。而简单工厂模式在添加新产品对象后不得不修改工厂方法,扩展性不好。工厂方法模式退化后可以演变成简单工厂模式。
工厂模式实现步骤
1.提供一个抽象工厂类
:所有具体工厂类的父类
2.提供与产品对应的工厂类:负责实例化产品对象
3.提供一个抽象产品类: 所有产品的父类
4.提供一个或多个产品类:工厂方法模式所创建的具体实例对象
UML图使用Umbrello绘制
简单工程模式UML图
配置截图
使用Umbrello可直接生存C++代码
生成代码如下:
自编工程模式测试代码
#include <iostream>
#include <string>
using namespace std;
/*---------------------------------------------------------------*/
class Operation
{
public:
virtual double getResult(double numberA, double numberB) = 0;
};
/*---------------------------------------------------------------*/
class Add : public Operation
{
public:
double getResult(double numberA, double numberB)
{
return numberA + numberB;
}
};
class Sub : public Operation
{
public:
double getResult(double numberA, double numberB)
{
return numberA - numberB;
}
};
class Mul : public Operation
{
public:
double getResult(double numberA, double numberB)
{
return numberA * numberB;
}
};
/*---------------------------------------------------------------*/
class OperationFactory
{
public:
OperationFactory();
~OperationFactory();
static Operation *createOperation(string operate)
{
Operation *oper = nullptr;
if(operate == "+")
{
oper = new Add;
}
else if(operate == "-")
{
oper = new Sub;
}
else
{
oper = new Mul;
}
return oper;
}
};
/*---------------------------------------------------------------*/
/*---------------------------------------------------------------*/
class AbstractProduct
{
public:
virtual void makeProduct() = 0;
};
class AbstractFactory
{
public:
virtual AbstractProduct* createProduct() = 0;
};
class PlaneProduct :public AbstractProduct
{
public:
void makeProduct()
{
cout << "造飞机....." << endl;
}
};
class PlaneFactory :public AbstractFactory
{
public:
AbstractProduct* createProduct()
{
AbstractProduct* product = new PlaneProduct;
return product;
}
};
class RocketProduct :public AbstractProduct
{
public:
void makeProduct()
{
cout << "造火箭...." << endl;
}
};
class RocketFactory :public AbstractFactory
{
public :
AbstractProduct* createProduct()
{
AbstractProduct* product = new RocketProduct;
return product;
}
};
int main()
{
Operation *add_oper = OperationFactory::createOperation("+");
cout << add_oper->getResult(20.5, 30.5) <<endl;
Operation *sub_oper = OperationFactory::createOperation("-");
Operation *mul_oper = OperationFactory::createOperation("#");
cout << sub_oper->getResult(20.5, 30.5) <<endl;
cout << mul_oper->getResult(20.5, 30.5) <<endl;
//造飞机
AbstractFactory* factory = new PlaneFactory;
AbstractProduct* product = factory->createProduct();
product->makeProduct();
//造火箭
factory = new RocketFactory;
product = factory->createProduct();
product->makeProduct();
return 0;
}
运行结果:
(完)