本文将通过具体实例详细解析PHP中的工厂方法设计模式,内容旨在为读者提供实用的参考与学习价值。
工厂方法模式的定义与核心概念
一、工厂方法模式的定义
工厂方法模式属于创建型设计模式的一种,其核心目标是负责创建“特定对象”。在该模式中,被创建的对象被称为产品,且产品的类与其创建者类之间保持解耦,不存在直接的绑定关系。为了实现这种松耦合架构,客户端代码通常不直接实例化产品,而是向工厂发起请求,由工厂负责生成所需的产品。借助工厂方法模式,请求方仅需提出需求,无需关心具体的产品创建逻辑。
工厂方法模式的适用场景
二、工厂方法模式的适用场景
当系统中需要实例化的对象子类存在不确定性或可能发生变化时,应当采用工厂方法模式。
一般工厂方法模式的实现特点
三、一般工厂方法模式
在一般工厂方法模式的应用中,客户端仅持有对工厂类的引用,且每个工厂类专门负责生产单一类型的产品。这种结构下,若需新增一种产品类型,必须同时创建一个对应的新工厂类和一个新产品类。
<?php
/**
* 一般工厂方法设计模式
**/
//工厂抽象类
abstract class Factory
{
protected abstract function produce();
public function startFactory()
{
$pro = $this->produce();
return $pro;
}
}
//文本工厂
class TextFactory extends Factory
{
protected function produce()
{
$textProduct = new TextProduct();
return $textProduct->getProperties();
}
}
//图像工厂
class ImageFactory extends Factory
{
protected function produce()
{
$imageProduct = new ImageProduct();
return $imageProduct->getProperties();
}
}
//产品类接口
interface Product
{
public function getProperties();
}
//文本产品
class TextProduct implements Product
{
private $text;
function getProperties()
{
$this->text = "此处为文本";
return $this->text;
}
}
//图像产品
class ImageProduct implements Product
{
private $image;
function getProperties()
{
$this->image = "此处为图像";
return $this->image;
}
}
//客户类
class Client
{
private $textFactory;
private $imageFactory;
public function __construct()
{
$this->textFactory = new TextFactory();
echo $this->textFactory->startFactory() . '
';
$this->imageFactory = new ImageFactory();
echo $this->imageFactory->startFactory() . '
';
}
}
$client = new Client();
/*运行结果:
此处为文本
此处为图像
*/
?>
参数化工厂方法模式的优化与对比
四、参数化工厂方法模式
在参数化工厂方法模式中,客户端同时持有工厂和产品的引用。在发出创建请求时,客户端需要明确指定所需产品的种类,此时一个工厂类可以负责生产多种不同类型的产品。相较于一般模式,这种方式的扩展性更强:当需要增加一种新产品时,只需新增一个对应的产品类,而无需修改工厂类或新增工厂类。
<?php
/**
* 参数化工厂方法设计模式
**/
//工厂抽象类
abstract class Factory
{
protected abstract function produce(Product $product);
public function startFactory(Product $product)
{
$pro = $this->produce($product);
return $pro;
}
}
//工厂实现
class ConcreteFactory extends Factory
{
protected function produce(Product $product)
{
return $product->getProperties();
}
}
//产品类接口
interface Product
{
public function getProperties();
}
//文本产品
class TextProduct implements Product
{
private $text;
public function getProperties()
{
$this->text = "此处为文本";
return $this->text;
}
}
//图像产品
class ImageProduct implements Product
{
private $image;
public function getProperties()
{
$this->image = "此处为图像";
return $this->image;
}
}
//客户类
class Client
{
private $factory;
private $textProduct;
private $imageProduct;
public function __construct()
{
$factory = new ConcreteFactory();
$textProduct = new TextProduct();
$imageProduct = new ImageProduct();
echo $factory->startFactory($textProduct) . '
';
echo $factory->startFactory($imageProduct) . '
';
}
}
$client = new Client();
/*运行结果:
此处为文本
此处为图像
*/
?>
希望上述关于PHP工厂方法模式的解析能对您的程序设计工作有所帮助。