神的尾巴

全栈工程师、独立开发者

0%

聊聊设计模式-创建型

纯手写,可能有错误,欢迎指出

简单工厂模式

使用静态方法,传递产品参数,返回对应的产品。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 简单工厂
class Factory
{
public static function create($productType)
{
if($productType == 'A') {
return new ProductA();
} elseif ($productType == 'B') {
return new ProductB();
} else {
return new Product();
}
}
}

工厂模式

由工厂子类,来返回指定的产品。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 工厂抽象类
interface Factory
{
public function create();
}

// 实现类工厂A
class FactoryA implements Factory
{
public funtion create()
{
return new ProductA();
}
}

抽象工厂模式

工厂模式一个工厂方法对应一个产品,对于那些需要一个工厂提供多个产品的,可以使用抽象工厂模式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//工厂抽象类
interface Factory
{
pulic function createA();
pulic function createB();
}

// 实现类工厂1
class Factory1 implements Factory
{
public function createA()
{
return new ProductA1();
}
public function createB()
{
return new ProductB1();
}
}

原型模式

用于快速复制对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 原型接口,包含clone方法
interface Prototype
{
public function clone();
}

// 原型实现类
class ConcretePrototype implements Protype
{
private $attr;
public function setAttr($attr)
{
$this->attr = $attr;
}
public function getAttr()
{
return $this->attr;
}
public function clone()
{
Prototype prototype = new ConcretePrototype();
prototype.setAttr($this->attr);
return prototype;
}
}

建造者模式

处理复杂对象的构建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// 指挥者,负责具体构建逻辑
class Director
{
private $builder;
public function setBuilder($builder)
{
$this->builder = $builder;
}
public function create()
{
$this->builder->builderPart1();
$this->builder->builderPart2();
$this->builder->builderPart3();
return $this->builder->getProduct();
}
}

// 建造者抽象类
abstruct class Builder
{
protected $product;
public function __construct()
{
$this->product = new Product();
}
abstruct function builderPart1();
abstruct function builderPart2();
abstruct function builderPart3();
public function getProduct()
{
return $this->product;
};
}

// 建造者实现类A
class BuilderA extends Builder
{
public function builderPart1()
{
$this->product->setpart1('A');
}
public function builderPart2()
{
$this->product->setpart2('A');
}
public function builderPart3()
{
$this->product->setpart3('A');
}
}

单例模式

用来创建单个实例

1
2
3
4
5
6
7
8
9
10
11
12
class Single 
{
private static $instance;

public static function getInstance()
{
if(!self::$instance) {
self::$instance = new Single();
}
return self::$instance;
}
}
觉得对你有帮助的话,请我喝杯咖啡吧~.