1.简单工厂模式:(简单工厂模式不属于23种设计模式)
结构图:
优点:统一接口
缺点:违背了“开闭原则”
代码实现:
生产类:
class Product{
public:
virtual void getName() = 0;
};
class ProductA:public Product{
public:
void getName(){
cout << "A产品" << endl;
}
};
class ProductB:public Product{
public:
void getName(){
cout << "B产品" << endl;
}
};
class ProductC:public Product{
public:
void getName(){
cout << "C产品" << endl;
}
};
工厂类:
class Factory{
public:
Product* send(string str){
if (str == "A"){
return new ProductA;
}
else if (str == "B"){
return new ProductB;
}
else if (str == "C"){
return new ProductC;
}
else{
return NULL;
}
}
};
测试代码:
int main(void){
Factory *fas= new Factory();
Product *pc = fas->send("A");
pc->getName();
delete fas, pc;
system("pause");
return 0;
}
调试结果:
简单工厂:
如果想在增加一种产品,那么就要更改工厂类中的代码。为了解决这个问题,将工厂类抽象,用那种产品就new那个工厂。
结构图:
代码实现:
生产类不变。
工厂类:
class Factory{
public:
virtual Product* send() = 0;
};
class FactoryA :public Factory{
Product* send(){
return new ProductA();
}
};
class FactoryB :public Factory{
Product* send(){
return new ProductB;
}
};
class FactoryC :public Factory{
Product* send(){
return new ProductC();
}
};
测试代码:
int main(void){
Factory *fas= new FactoryB();
Product *pb = fas->send();
pb->productDo();
delete fas, pb;
system("pause");
return 0;
}
调试结果:
缺点:
每个子工厂的功能过于单一。
抽象工厂模式:
工厂模式只能生产一个产品,抽象工厂可以生产一个产品族。
结构图:
水果类:
class Fruit{
public:
virtual void getName()=0;
};
class SouthApple :public Fruit{
public:
void getName(){
cout << "SouthApple" << endl;
}
};
class SouthPear :public Fruit{
public:
void getName(){
cout << "SouthPear" << endl;
}
};
class NorthApple :public Fruit{
public:
void getName(){
cout << "NorthApple" << endl;
}
};
class NorthPear :public Fruit{
public:
void getName(){
cout << "NorthPear"<<endl;
}
};
工厂:
class Factory{
virtual Fruit* CreatApple() = 0;
virtual Fruit* CreatPear() = 0;
};
class FactoryNorth :public Factory{
public:
Fruit* CreatApple(){
return new NorthApple();
}
Fruit* CreatPear(){
return new NorthPear();
}
};
class FactorySouth :public Factory{
public:
Fruit* CreatApple(){
return new SouthApple();
}
Fruit* CreatPear(){
return new SouthPear;
}
};
测试代码:
int main(void){
FactoryNorth *fac = new FactoryNorth();
Fruit *apple = fac->CreatApple();
apple->getName();
Fruit *pear = fac->CreatPear();
pear->getName();
delete apple, pear,fac;
system("pause");
return 0;
}
调试结果: