一、概述
和简单工厂模式一样,不属于23种标准设计模式,属于一种编程风格。将简单工厂模式的类改为静态
二、核心
相对于简单工厂模式,工厂方法为静态
三、代码示例
<?php
/*
* 静态工厂模式(Static Factory)
*/
interface AnimalInterface
{
public function run();
}
class Cat implements AnimalInterface
{
public function run()
{
return "Cat Run";
}
}
class Dog implements AnimalInterface
{
public function run()
{
return "Dog Run";
}
}
Class Staticfactory
{
public static function createAnimal($className): AnimalInterface
{
switch ($className){
case "Cat":
return new Cat();
case "Dog":
return new Dog();
default:
return false;
}
return new $className();
}
}
$cat = Staticfactory::createAnimal('Cat');
$cat->run();