一、概述
简单理解为根据传递的参数不同,获取相应的对象
二、核心
- 对简单工厂模式进行抽象化,可以实现一个抽象工厂类可以派生出多个工厂类
- 真正实现了SOLID中的D【依赖倒置】
- 属于设计模式中的“创建型设计模式”
三、结构图
四、代码示例
<?php
/*
* 工厂方法模式(Factory Method)
*/
interface AnimalInterface
{
public function run();
public function eat();
}
class Cat implements AnimalInterface
{
public function run()
{
return "Cat Run";
}
public function eat()
{
return "Cat eat";
}
}
class Dog implements AnimalInterface
{
public function run()
{
return "Dog Run";
}
public function eat()
{
return "Dog eat";
}
}
interface FactoryInterface{
public static function createAnimal();
}
class CatFactory implements FactoryInterface
{
public static function createAnimal(): AnimalInterface
{
return new Cat();
}
}
class DogFactory implements FactoryInterface
{
public static function createAnimal(): AnimalInterface
{
return new Dog();
}
}
$cat = CatFactory::createAnimal();
$cat->eat();
$cat->run();
$dog = DogFactory::createAnimal();
$dog->eat();
$dog->run();
五、总结
- 一个抽象类可以派生出多个具体产品类(AnimalInterface=>[CatClass, DogClass])
- 一个抽象工厂类可以派生出多个具体工厂类(FactoryInterface=>[CatFactory, DogFactory])
- 每个具体工厂类只能创建一个具体产品类的实例(CatFactory=>CatClass、DogFactory=>DogClass)