工厂模式
工厂方法模式
对比简单工厂模式的优点是,您可以将其子类用不同的方法来创建一个对象。
举一个简单的例子,这个抽象类可能只是一个接口。
这种模式是「真正」的设计模式, 因为他实现了S.O.L.I.D原则中「D」的 「依赖倒置」。
这意味着工厂方法模式取决于抽象类,而不是具体的类。 这是与简单工厂模式和静态工厂模式相比的优势。
FactoryMethod.php
<?php
namespace DesignPatterns\Creational\FactoryMethod;
abstract class FactoryMethod //可以被继承创建不同的工厂,
{
const CHEAP = 'cheap';
const FAST = 'fast';
abstract protected function createVehicle(string $type): VehicleInterface; //关键在于这个方法可以创建不同的子类
public function create(string $type): VehicleInterface
{
$obj = $this->createVehicle($type);
$obj->setColor('black');
return $obj;
}
}
talianFactory.php
<?php
namespace DesignPatterns\Creational\FactoryMethod;
class ItalianFactory extends FactoryMethod//不同工厂
{
protected function createVehicle(string $type): VehicleInterface
{
switch ($type) {
case parent::CHEAP:
return new Bicycle();
case parent::FAST:
return new CarFerrari();
default:
throw new \InvalidArgumentException("$type is not a valid vehicle");
}
}
}
GermanFactory.php
<?php
namespace DesignPatterns\Creational\FactoryMethod;
class GermanFactory extends FactoryMethod //不同的工厂
{
protected function createVehicle(string $type): VehicleInterface
{
switch ($type) {
case parent::CHEAP:
return new Bicycle();
case parent::FAST:
$carMercedes = new CarMercedes();
// 我们可以从已知的的类中找到具体的交通工具
$carMercedes->addAMGTuning();
return $carMercedes;
default:
throw new \InvalidArgumentException("$type is not a valid vehicle");
}
}
}
VehicleInterface.php
<?php
namespace DesignPatterns\Creational\FactoryMethod;
interface VehicleInterface //子类接口
{
public function setColor(string $rgb);
}
CarMercedes.php
<?php
namespace DesignPatterns\Creational\FactoryMethod;
class CarMercedes implements VehicleInterface //不同的子类
{
/**
* @var string
*/
private $color;
public function setColor(string $rgb)
{
$this->color = $rgb;
}
public function addAMGTuning()
{
// 在这里做额外的调整
}
}
CarFerrari.php
<?php
namespace DesignPatterns\Creational\FactoryMethod;
class CarFerrari implements VehicleInterface//不同的子类
{
/**
* @var string
*/
private $color;
public function setColor(string $rgb)
{
$this->color = $rgb;
}
}
Bicycle.php
<?php
namespace DesignPatterns\Creational\FactoryMethod;
class Bicycle implements VehicleInterface//不同的子类
{
/**
* @var string
*/
private $color;
public function setColor(string $rgb)
{
$this->color = $rgb;
}
}
静态工厂模式
<?php
namespace DesignPatterns\Creational\StaticFactory;
/**
* 注意点1: 记住,静态意味着全局状态,因为它不能被模拟进行测试,所以它是有弊端的
* 注意点2: 不能被分类或模拟或有多个不同的实例。
*/
final class StaticFactory
{
/**
* @param string $type
*
* @return FormatterInterface
*/
public static function factory(string $type): FormatterInterface
{
if ($type == 'number') {
return new FormatNumber();
}
if ($type == 'string') {
return new FormatString();
}
throw new \InvalidArgumentException('Unknown format given');
}
}