1.工厂方法模式简介
工厂方法模式定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
2.源码实现
<?php
/*抽象工厂类*/
abstract class Factory {
protected abstract function produce();
public function startFactory()
{
$pro = $this->produce();
return $pro;
}
}
/*产品类接口*/
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 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();
}
}
/*客户类*/
class Client {
private $textFactory;
private $imageFactory;
public function __construct()
{
$this->textFactory = new TextFactory();
echo $this->textFactory->startFactory()."\n";
$this->imageFactory = new ImageFactory();
echo $this->imageFactory->startFactory()."\n";
}
}
$client = new Client();
?>
3.运行及其结果
$ php example.php
此处为文本
此处为图像
网友评论