简介
简单工厂模式有一个问题就是,类的创建依赖工厂类,也就是说,如果想要拓展程序,必须对工厂类进行修改,这违背了闭包原则,所以,从设计角度考虑,有一定的问题,如何解决?就用到工厂方法模式,创建一个工厂接口和创建多个工厂实现类,这样一旦需要增加新的功能,直接增加新的工厂类就可以了,不需要修改之前的代码。
角色与职责
实现
#include <iostream>
using namespace std;
class Product{
public:
virtual void Show() = 0;
};
class ProductA : public Product{
public:
void Show(){
cout << "I'm ProductA" << endl;
}
};
class ProductB : public Product{
public:
void Show(){
cout << "I'm ProductB" << endl;
}
};
class Factory{
public:
virtual Product *CreateProduct() = 0;
};
class FactoryA : public Factory{
public:
Product *CreateProduct(){
return new ProductA();
}
};
class FactoryB : public Factory{
public:
Product *CreateProduct(){
return new ProductB();
}
};
int main(int argc, char *argv[]){
Factory *factoryA = new FactoryA();
Product *productA = factoryA->CreateProduct();
productA->Show();
Factory *factoryB = new FactoryB();
Product *productB = factoryB->CreateProduct();
productB->Show();
if (factoryA != NULL){
delete factoryA;
factoryA = NULL;
}
if (productA != NULL){
delete productA;
productA = NULL;
}
if (factoryB != NULL){
delete factoryB;
factoryB = NULL;
}
if (productB != NULL){
delete productB;
productB = NULL;
}
return 0;
}