抽象工厂模式是相对于工厂模式而言的,若未看过上一篇工厂模式,请先看上一篇工厂模式:http://blog.csdn.net/phenixsoul/article/details/8486571
抽象工厂模式是对工厂模式的抽象,通俗来说,就是把工厂模式的结构分离出来成为能独立运行的个体。
还是拿工厂模式中的例子来说明:
现在有一个汽车工厂,它生产小汽车和巴士车,小汽车和巴士车都是由引擎、车身和轮子组成的。
在工厂模式中,我们把小汽车和巴士车作为汽车族群中的两个类别,生产引擎、车身和轮子为生产汽车的固定结构,如下图所示:
在抽象工厂模式中,把生产引擎、车身和轮子分别抽象出来,如下图所示:
实际部署为:
//生产引擎的标准
interface engineNorms{
function engine();
}
class carEngine implements engineNorms{
public function engine(){
return '汽车引擎';
}
}
class busEngine implements engineNorms{
public function engine(){
return '巴士车引擎';
}
}
//生产车身的标准
interface bodyNorms{
function body();
}
class carBody implements bodyNorms{
public function body(){
return '汽车车身';
}
}
class busBody implements bodyNorms{
public function body(){
return '巴士车车身';
}
}
//生产车轮的标准
interface whellNorms{
function whell();
}
class carWhell implements whellNorms{
public function whell(){
return '汽车轮子';
}
}
class busWhell implements whellNorms{
public function whell(){
return '巴士车轮子';
}
}
再继续对工厂进行抽象,抽象出汽车工厂和巴士车工厂,并且让各工厂与各组件相关联,如图:
实际部署为:
//生产引擎的标准
interface engineNorms{
function engine();
}
class carEngine implements engineNorms{
public function engine(){
return '汽车引擎';
}
}
class busEngine implements engineNorms{
public function engine(){
return '巴士车引擎';
}
}
//生产车身的标准
interface bodyNorms{
function body();
}
class carBody implements bodyNorms{
public function body(){
return '汽车车身';
}
}
class busBody implements bodyNorms{
public function body(){
return '巴士车车身';
}
}
//生产车轮的标准
interface whellNorms{
function whell();
}
class carWhell implements whellNorms{
public function whell(){
return '汽车轮子';
}
}
class busWhell implements whellNorms{
public function whell(){
return '巴士车轮子';
}
}
//工厂标准
interface factory{
static public function getInstance($type);
}
//汽车工厂
class carFactory implements factory{
static public function getInstance($type){
$instance='';
switch($type){
case 'engine':
$instance=new carEngine();
break;
case 'body':
$instance=new carBody();
break;
case 'whell':
$instance=new carWhell();
break;
default:
throw new Exception('汽车工厂无法生产这种产品');
}
return $instance;
}
}
//巴士车工厂
class busFactory implements factory{
static public function getInstance($type){
$instance='';
switch($type){
case 'engine':
$instance=new busEngine();
break;
case 'body':
$instance=new busBody();
break;
case 'whell':
$instance=new busWhell();
break;
default:
throw new Exception('巴士车工厂无法生产这种产品');
}
return $instance;
}
}
$car['engine']=carFactory::getInstance('engine')->engine();
$car['body']=carFactory::getInstance('body')->body();
$car['whell']=carFactory::getInstance('whell')->whell();
print_r($car);
$bus['engine']=busFactory::getInstance('engine')->engine();
$bus['body']=busFactory::getInstance('body')->body();
$bus['whell']=busFactory::getInstance('whell')->whell();
print_r($bus);
抽象工厂模式将工厂模式进行抽象,可以使得抽象出来的新结构更加的灵活。例如,若生产车身需要一个喷漆的动作,在工厂模式中,我们需要对整体结构进行更改,而抽象工厂中,只需要对生产车身进行更改就ok了。
抽象工厂模式同样具有工厂模式对结构要求高的缺点,整体结构的扩展或精简将变得更加的烦杂,所以使用抽象工厂模式时,对等级结构的划分是非常重要的。