转自:https://blog.csdn.net/jigetage/article/details/79605624 作了一点修改。
工厂模式分为3种,即简单工厂模式、工厂方法模式、抽象工厂模式,其实大同小异,总结下来就是:
简单工厂模式:一个工厂,多个产品。产品需要有一个虚基类。通过传入参数,生成具体产品对象,并利用基类指针指向此对象。通过工厂获取此虚基类指针,通过运行时多态,调用子类实现。
// Factory.cpp : 定义控制台应用程序的入口点。
//
#include<iostream>
using namespace std;
class Product
{
public:
virtual void show() = 0;
};
class Product_A : public Product
{
public:
void show()
{
cout << "Product_A" << endl;
}
};
class Product_B : public Product
{
public:
void show()
{
cout << "Product_B" << endl;
}
};
class Factory
{
public:
Product* Create(int i)
{
switch (i)
{
case 1:
return new Product_A;
break;
case 2:
return new Product_B;
break;
default:
break;
}
}
};
int main()
{
Factory *factory = new Factory();
factory->Create(1)->show();
factory->Create(2)->show();
system("pause");
return 0;
}
工厂方法模式:多个工厂,多个产品,每个产品对应于一个工厂。此时工厂和产品都是通过虚基类的方式构建。对于简单工厂模式,当要增加一个新产品时候,就需要在工厂类中修改代码,具体表现为多加一个参数,来识别新的产品类型。此时违反了对扩展开放,对修改关闭的原则。基于此,工厂方法模式应运而生。当增加一个新产品时,同时增加一个新工厂。增加新工厂属于扩展,不会修改以前工厂类和产品类的任何代码。可以看过多个独立的简单工厂模式构成了工厂方法模式。
#include<iostream>
using namespace std;
class Product
{
public:
virtual void show() = 0;
};
class Product_A : public Product
{
public:
void show()
{
cout << "Product_A" << endl;
}
};
class Product_B : public Product
{
public:
void show()
{
cout << "Product_B" << endl;
}
};
class Factory
{
public:
virtual Product* create() = 0;
};
class Factory_A : public Factory
{
public:
Product* create()
{
return new Product_A;
}
};
class Factory_B : public Factory
{
public:
Product* create()
{
return new Product_B;
}
};
int main()
{
Factory* productA = new Factory_A();
Factory* productB = new Factory_B();
productA->create()->show();
productB->create()->show();
system("pause");
return 0;
}
抽象工厂模式:多个工厂,多个产品,并且每个产品可以包含多个型号。此时工厂和产品都是通过虚基类的方式构建。每一个工厂类可以生产同一个产品的多个型号。
#include <iostream>
using namespace std;
//定义抽象类
class product1
{
public:
virtual void show() = 0;
};
//定义具体类
class product_A1 :public product1
{
public:
void show(){ cout << "product A1" << endl; }
};
class product_B1 :public product1
{
public:
void show(){ cout << "product B1" << endl; }
};
//定义抽象类
class product2
{
public:
virtual void show() = 0;
};
//定义具体类
class product_A2 :public product2
{
public:
void show(){ cout << "product A2" << endl; }
};
class product_B2 :public product2
{
public:
void show(){ cout << "product B2" << endl; }
};
class Factory
{
public:
virtual product1 *creat1() = 0;
virtual product2 *creat2() = 0;
};
class FactoryA :public Factory
{
public:
product1 *creat1(){ return new product_A1(); }
product2 *creat2(){ return new product_A2(); }
};
class FactoryB :public Factory
{
public:
product1 *creat1(){ return new product_B1(); }
product2 *creat2(){ return new product_B2(); }
};
int main()
{
Factory *factory = new FactoryA();
factory->creat1()->show();
factory->creat2()->show();
Factory *factory1 = new FactoryB();
factory1->creat1()->show();
factory1->creat2()->show();
return 0;
}