一、概述
抽象工厂模式是围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。这种类型的设计模式属于创建型模式。
二、核心
通过一个超级工厂管理所有的子工厂,把工厂模式的结构分离出来成为能独立运行的个体
三、架构图
四、代码示例
<?php
/*
* 抽象工厂模式(Factory Method)
*/
interface RunInterface
{
public function exec();
}
class CatRun implements RunInterface
{
public function exec()
{
return 'Cat Run';
}
}
class DogRun implements RunInterface
{
public function exec()
{
return 'Dog Run';
}
}
interface EatInterfact
{
public function exec();
}
class CatEat implements EatInterfact
{
public function exec()
{
return 'Cat Eat';
}
}
class DogEat implements EatInterfact
{
public function exec()
{
return 'Dog Eat';
}
}
interface FactoryInterface
{
public static function createAnimal($type);
}
class CatFactory implements FactoryInterface
{
//方法一
public static function createAnimal($type)
{
switch ($type){
case "Run":
return new CatRun();
case "Eat":
return new CatEat();
default:
return false;
}
}
//方法二
public static function createCatRun()
{
return new CatRun();
}
public static function createCatEat()
{
return new CatEat();
}
}
class DogFactory implements FactoryInterface
{
//方法一
public static function createAnimal($type)
{
switch ($type){
case "Run":
return new DogRun();
case "Eat":
return new DogEat();
default:
return false;
}
}
//方法二
public static function createDogRun()
{
return new DogRun();
}
public static function createDogEat()
{
return new DogEat();
}
}
//方法一
$cat['run'] = CatFactory::createAnimal('Run')->exec();
$cat['eat'] = CatFactory::createAnimal('Eat')->exec();
//方法二
$cat['2run'] = CatFactory::createCatRun()->exec();
$cat['2eat'] = CatFactory::createCatEat()->exec();
//方法一
$dog['run'] = DogFactory::createAnimal('Run')->exec();
$dog['eat'] = DogFactory::createAnimal('Eat')->exec();
//方法二
$dog['2run'] = DogFactory::createDogRun()->exec();
$dog['2eat'] = DogFactory::createDogEat()->exec();
五、总结
- 一个抽象产品类派生多个具体产品类(EatInterface=>[CatEatClass,DogEatClass], RunInterface=>[CatRunClass, DogRunclass])
- 一个抽象工厂类可以派生出多个具体工厂类(FactoryInterface=>[CatFactory, DogFactory])
- 每个具体的工厂类创建多个具体的产品实例({CatFactory=>[CatEatClass, CatRunClass], DogFactory=>[DogRunClass, DogEatClass]})