这次给大家带来PHP工厂方法设计模式案例详解,PHP工厂方法设计模式案使用的注意事项有哪些,下面就是实战案例,一起来看一下。
一、什么是工厂方法模式
作为一种创建型设计模式,工厂方法模式就是要创建“某种东西”。对于工厂方法,要创建的“东西”是一个产品,这个产品与创建它的类之间不存在绑定。实际上,为了保持这种松耦合,客户会通过一个工厂发出请求,再由工厂创建所请求的产品。利用工厂方法模式,请求者只发出请求,而不具体创建产品。
二、什么时候使用工厂方法模式
如果实例化对象的子类可能改变,就要使用工厂方法模式。
三、一般工厂方法模式
使用一般工厂方法模式时,客户只包含工厂的引用,一个工厂生产一种产品。增加一种产品的同时需要增加一个新工厂类和一个新产品类。
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();
/*运行结果:
此处为文本
此处为图像
*/
?>四、参数化工厂方法模式
使用参数化工厂方法模式时,客户包含工厂和产品的引用,发出请求时需要指定产品的种类,一个工厂生产多种产品。增加一种产品时只需要增加一个新产品类即可。
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中文网其它相关文章!
推荐阅读:
PHP5学习对象教程由美国人古曼兹、贝肯、瑞桑斯编著,简张桂翻译,电子工业出版社于2007年12月1日出版的关于PHP5应用程序的技术类图书。该书全面介绍了PHP 5中的新功能、编程方法及设计模式,还分析阐述了PHP 5中新的数据库连接处理、错误处理和XML处理等机制,帮助读者系统了解、熟练掌握和高效应用PHP。










