php设计模式之生成对象

创建对象是一件棘手的事情。利用多态带来的灵活性(在运行时切换不同的具体实现) ,我们可以采用多种面向对象设计方案来处理优美且简洁的抽象类。为了达到这样的灵活性 ,我们必须仔细考虑生成对象的策略。

对象创建有时会成为面向对象设计的一个薄弱环节。面向对象有一个原则:“针对接口编程,而不是针对实现编程”。所以,我们鼓励使用抽象类或接口,这使代码更具灵活性,可以让你在运行时使用从不同的具体子类中实例化对象。但这样做也有副作用,那就是对象实例化被推迟了。

直接使用new创建对象

demo1.php

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
<?php
header('Content-Type:text/html; charset=utf-8');

abstract class Person{
protected $name;
public function __construct($name){
$this->name = $name;
}
abstract public function doing();
}

class Student extends Person{
public function doing(){
return '学生'.$this->name.'在学习!';
}
}

class Teacher extends Person{
public function doing(){
return '老师'.$this->name.'在讲课!';
}
}

$person = new Student('小胡');
echo $person->doing();

# 使用引导类创建对象

demo2.php

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
<?php
header('Content-Type:text/html; charset=utf-8');

abstract class Person{
protected $name;
public function __construct($name){
$this->name = $name;
}
abstract public function doing();
}

class Student extends Person{
public function doing(){
return '学生'.$this->name.'在学习!';
}
}

class Teacher extends Person{
public function doing(){
return '老师'.$this->name.'在讲课!';
}
}

class Lead{
private $person;

public function addPerson(Person $person){
$this->person = $person;
}

public function doing(){
return $this->person->doing();
}
}

$person = new Lead();
$person->addPerson(new Student('小胡'));
echo $person->doing();

使用工厂创建对象

demo3.php

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
<?php
header('Content-Type:text/html; charset=utf-8');

abstract class Person{
protected $name;
public function __construct($name){
$this->name = $name;
}
abstract public function doing();
}

class Student extends Person{
public function doing(){
return '学生'.$this->name.'在学习!';
}
}

class Teacher extends Person{
public function doing(){
return '老师'.$this->name.'在讲课!';
}
}

class Lead{
static private $types = ['Student', 'Teacher'];
static public function getPerson($name){
return new self::$types[0]($name);
}
}

$person = Lead::getPerson('小胡');
echo $person->doing();

在代码块中,我们发现客户端不需要 new 很多对象了,将对象实例化的工作委托给了静态方法,静态方法根据场景的不同而生产不同的对象实例。这种生成对象的方法,我们称作为工厂。