1.简单工厂模式
简单工厂模式,工厂类是创建产品的,它决定创建哪一种产品,就像领导决定采用那种技术方案样。举个例子,现在有宝马车和奔驰车两种车需要生产,但是只有一个工厂,且只能在同一时间生产一种车,这时就有工厂决定生产那种车了。
一个工厂,多个产品。产品需要有一个虚基类。通过传入参数,生成具体产品对象,并利用基类指针指向此对象。通过工厂获取此虚基类指针,通过运行时多肽,调用子类实现。
// Factory.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#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;
}
2.工厂方法模式
是指定义一个创建对象的接口,让子类决定实例化哪一个类,Factory Method使一个类的实例化延迟到其子类。
意图:定义一个创建对象的接口, 让其子类自己决定实例化哪一个工厂类,工厂模式使其创建过程延迟到子类进行。
多个工厂,多个产品,每个产品对应于一个工厂。此时工厂和产品都是通过虚基类的方式构建。对于简单工厂模式,当要增加一个新产品时候,就需要在工厂类中修改代码,具体表现为多加一个参数,来识别新的产品类型。此时违反了对扩展开放,对修改关闭的原则。基于此,工厂方法模式应运而生。当增加一个新产品时,同时增加一个新工厂。增加新工厂属于扩展,不会修改以前工厂类和产品类的任何代码。可以看过多个独立的简单工厂模式构成了工厂方法模式。
工厂方法图解
#include "stdafx.h"
#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_A* productA = new Factory_A();
Factory_B* productB = new Factory_B();
productA->create()->show();
productB->create()->show();
system("pause");
return 0;
}
3.抽象工厂模式:
多个工厂,多个产品,并且每个产品可以包含多个型号。此时工厂和产品都是通过虚基类的方式构建。每一个工厂类可以生产同一个产品的多个型号。
提供一个创建一系列相关或相互依赖的对象接口,而无需指定它们的具体类;
主要解决:接口选择的问题。
抽象工厂图解
class Tank
{
public:
virtual void message() = 0;
};
class Tank80:public Tank
{
public:
void message()
{
cout << "Tank80" << endl;
}
};
class Tank99:public Tank
{
public:
void message()
{
cout << "Tank99" << endl;
}
};
class Plain
{
public:
virtual void message() = 0;
};
class Plain80: public Plain
{
public:
void message()
{
cout << "Plain80" << endl;
}
};
class Plain99: public Plain
{
public:
void message()
{
cout << "Plain99" << endl;
}
};
class Factory
{
public:
virtual Tank* createTank() = 0;
virtual Plain* createPlain() = 0;
};
class Factory80:public Factory
{
public:
Tank* createTank()
{
return new Tank80();
}
Plain* createPlain()
{
return new Plain80();
}
};
class Factory99:public Factory
{
public:
Tank* createTank()
{
return new Tank99();
}
Plain* createPlain()
{
return new Plain99();
}
};