工厂模式分为三种类型,分别是简单工厂,工厂方法和抽象工厂。这三种类型的实现都和虚函数分不开。
一.简单工厂
class Product
{
public:
virtual int fun(int a, int b) = 0;
};
class ProductAdd : public Product
{
public:
int fun(int a, int b) {
return a + b;
}
};
class ProductMul : public Product
{
public:
int fun(int a, int b) {
return a * b;
}
};
class Factory
{
public:
Product* create(int i) {
switch (i) {
case 1: return new ProductAdd; break;
case 2: return new ProductMul; break;
default:; break;
}
//return new ProductAdd;
}
};
int main()
{
Factory *fac = new Factory;
cout << fac->create(1)->fun(2, 3) << endl;
cout << fac->create(2)->fun(2, 3) << endl;
return 0;
}
假如添加一个减法,需要改之前实现的部分,不方便维护,这有违软件开发的开放-封闭原则。
二.工厂方法
class Product
{
public:
virtual int fun(int a, int b) = 0;
};
class ProductAdd : public Product
{
public:
int fun(int a, int b) {
return a + b;
}
};
class ProductMul : public Product
{
public:
int fun(int a, int b) {
return a * b;
}
};
class Factory
{
public:
virtual Product* create() = 0;
};
class FactoryAdd : public Factory
{
public:
Product* create() {
return new ProductAdd;
}
};
class FactoryMul : public Factory
{
public:
Product* create() {
return new ProductMul;
}
};
int main()
{
Factory *facadd = new FactoryAdd;
Factory *facmul = new FactoryMul;
cout << facadd->create()->fun(2, 3) << endl;
cout << facmul->create()->fun(2, 3) << endl;
return 0;
}
工厂方法这种方式扩展新的产品时避免了修改之前的代码,但是每种工厂只能生产一种产品。
三.抽象工厂
class Product
{
public:
virtual int fun(int a, int b) = 0;
};
class ProductAdd : public Product
{
public:
int fun(int a, int b) {
return a + b;
}
};
class ProductMul : public Product
{
public:
int fun(int a, int b) {
return a * b;
}
};
class ProductN
{
public:
virtual int fun(int a, int b) = 0;
};
class ProductNAdd : public ProductN
{
public:
int fun(int a, int b) {
return (-a) + (-b);
}
};
class ProductNMul : public ProductN
{
public:
int fun(int a, int b) {
return (-a) * (-b);
}
};
class Factory
{
public:
virtual Product* create() = 0;
virtual ProductN* create_n() = 0;
};
class FactoryAdd : public Factory
{
public:
Product* create() {
return new ProductAdd;
}
ProductN* create_n() {
return new ProductNAdd;
}
};
class FactoryMul : public Factory
{
public:
Product* create() {
return new ProductMul;
}
ProductNMul* create_n() {
return new ProductNMul;
}
};
int main()
{
Factory *facadd = new FactoryAdd;
Factory *facmul = new FactoryMul;
cout << facadd->create()->fun(2, 3) << endl;
cout << facadd->create_n()->fun(2, 3) << endl;
cout << facmul->create()->fun(2, 3) << endl;
cout << facmul->create_n()->fun(2, 3) << endl;
return 0;
}
抽象工厂其实是前面两种方法的一个结合,相对于平行扩展了一个product,既没有违背开闭原则,又可以生产多种产品。
参考资料: