找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索本站精品资源

首页 教程频道 php教程 查看内容

设计模式

作者:模板之家 2020-10-25 20:26 5282人关注

设计模式按照作用可以分为3大类:创建型、结构型、行为型。 创建型设计模式工厂方法 参与者:客户、工厂、产品 场景:实例化对象的子类可能发生变化。 优点:方便修改,方便新增。 注意:client不会实例化所请求的产 ...

设计模式按照作用可以分为3大类:创建型、结构型、行为型。

创建型设计模式

工厂方法

  • 参与者:客户、工厂、产品
  • 场景:实例化对象的子类可能发生变化。
  • 优点:方便修改,方便新增。
  • 注意:client不会实例化所请求的产品,由具体的工厂实例化所请求的产品。

步骤:

1.创建工厂(工厂接口[抽象类])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
// 工厂方法模式
// 工厂接口(抽象类)
abstract class Creator
{
// 抽象方法
protected abstract function factoryMethod();
// 具体方法
public function startFactory()
{
$mfg = $this->factoryMethod();
return $mfg;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
// 具体工厂类(文字)
include_once('Creator.php');
include_once('TextProduct.php');
class TextFactory extends Creator
{
protected function factoryMethod()
{
// 工厂类实例化产品
$product = new TextProduct();
return($product->getProperties());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
// 具体工厂类(图像)
include_once('Creator.php');
include_once('GraphicProduct.php');
class GraphicFactory extends Creator
{
protected function factoryMethod()
{
// 工厂类实例化产品
$product = new GraphicProduct();
return($product->getProperties());
}
}

2.产品接口

1
2
3
4
5
6
<?php
// 产品接口
interface Product
{
public function getProperties();
}
1
2
3
4
5
6
7
8
9
10
11
12
<?php
// 具体产品类(文字)
include_once('Product.php');
class TextProduct implements Product
{
private $mfgProduct;
public function getProperties()
{
$this->mfgProduct = 'This is text';
return $this->mfgProduct;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
<?php
// 具体产品类(图像)
include_once('Product.php');
class GraphicProduct implements Product
{
private $mfgProduct;
public function getProperties()
{
$this->mfgProduct = 'This is graphic';
return $this->mfgProduct;
}
}

3.客户(客户并没有向产品直接做出请求,而是通过工厂来请求。)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
// 客户
include_once('GraphicFactory.php');
include_once('TextFactory.php');
class Client
{
private $someGraphicObject;
private $someTextObject;
public function __construct()
{
$this->someGraphicObject = new GraphicFactory();
echo $this->someGraphicObject->startFactory() . "\n";
$this->someTextObject = new TextFactory();
echo $this->someTextObject->startFactory() . "\n";
}
}
// 实例化客户
$worker = new Client();

未完待续


路过

雷人

握手

鲜花

鸡蛋
原作者: 网络收集 来自: 网络收集
上一篇:ansible入门
下一篇:Go之旅-for循环

全部回复(0)