
与高手过招内功不修炼好怎么能行,使用设计模式编写程序的好处网上一堆,一些优秀的PHP框架也无不体现着设计模式的妙处,简言之就是使用设计模式编写的程序易于理解、易于扩展、易于维护
网上有很多不错的文章,我就做个小小的搬运工
S.O.L.I.D 设计原则
SOLID 是Michael Feathers推荐的便于记忆的首字母简写,它代表了Robert Martin命名的最重要的五个面对对象编码设计原则,以下内容转自代码整洁之道PHP实现中文翻译版,原文地址:https://github.com/php-cpm/clean-code-php#solid
S: 单一职责原则 (SRP)Single Responsibility Principle
正如在Clean Code所述,”修改一个类应该只为一个理由”。 人们总是易于用一堆方法塞满一个类,如同我们只能在飞机上 只能携带一个行李箱(把所有的东西都塞到箱子里)。这样做 的问题是:从概念上这样的类不是高内聚的,并且留下了很多 理由去修改它。将你需要修改类的次数降低到最小很重要。 这是因为,当有很多方法在类中时,修改其中一处,你很难知 晓在代码库中哪些依赖的模块会被影响到。
坏的设计
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
class UserSettings
{
private $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function changeSettings(array $settings): void
{
if ($this->verifyCredentials()) {
// ...
}
}
private function verifyCredentials(): bool
{
// ...
}
}
|
好的设计
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
|
class UserAuth
{
private $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function verifyCredentials(): bool
{
// ...
}
}
class UserSettings
{
private $user;
private $auth;
public function __construct(User $user)
{
$this->user = $user;
$this->auth = new UserAuth($user);
}
public function changeSettings(array $settings): void
{
if ($this->auth->verifyCredentials()) {
// ...
}
}
}
|
O: 开闭原则 (OCP) Open/Closed Principle
正如Bertrand Meyer所述,”软件的工件( classes, modules, functions 等) 应该对扩展开放,对修改关闭。” 然而这句话意味着什么呢?这个原则大体上表示你 应该允许在不改变已有代码的情况下增加新的功能
坏的设计
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
51
52
53
54
55
56
57
58
59
60
|
abstract class Adapter
{
protected $name;
public function getName(): string
{
return $this->name;
}
}
class AjaxAdapter extends Adapter
{
public function __construct()
{
parent::__construct();
$this->name = 'ajaxAdapter';
}
}
class NodeAdapter extends Adapter
{
public function __construct()
{
parent::__construct();
$this->name = 'nodeAdapter';
}
}
class HttpRequester
{
private $adapter;
public function __construct(Adapter $adapter)
{
$this->adapter = $adapter;
}
public function fetch(string $url): Promise
{
$adapterName = $this->adapter->getName();
if ($adapterName === 'ajaxAdapter') {
return $this->makeAjaxCall($url);
} elseif ($adapterName === 'httpNodeAdapter') {
return $this->makeHttpCall($url);
}
}
private function makeAjaxCall(string $url): Promise
{
// request and return promise
}
private function makeHttpCall(string $url): Promise
{
// request and return promise
}
}
|
好的
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
|
interface Adapter
{
public function request(string $url): Promise;
}
class AjaxAdapter implements Adapter
{
public function request(string $url): Promise
{
// request and return promise
}
}
class NodeAdapter implements Adapter
{
public function request(string $url): Promise
{
// request and return promise
}
}
class HttpRequester
{
private $adapter;
public function __construct(Adapter $adapter)
{
$this->adapter = $adapter;
}
public function fetch(string $url): Promise
{
return $this->adapter->request($url);
}
}
|
L: 里氏替换原则 (LSP) Liskov Substitution Principle
这是一个简单的原则,却用了一个不好理解的术语。它的正式定义是 “如果S是T的子类型,那么在不改变程序原有既定属性(检查、执行 任务等)的前提下,任何T类型的对象都可以使用S类型的对象替代 (例如,使用S的对象可以替代T的对象)” 这个定义更难理解:-)。
对这个概念最好的解释是:如果你有一个父类和一个子类,在不改变 原有结果正确性的前提下父类和子类可以互换。这个听起来依旧让人 有些迷惑,所以让我们来看一个经典的正方形-长方形的例子。从数学 上讲,正方形是一种长方形,但是当你的模型通过继承使用了”is-a” 的关系时,就不对了。
坏的
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
|
class Rectangle
{
protected $width = 0;
protected $height = 0;
public function setWidth(int $width): void
{
$this->width = $width;
}
public function setHeight(int $height): void
{
$this->height = $height;
}
public function getArea(): int
{
return $this->width * $this->height;
}
}
class Square extends Rectangle
{
public function setWidth(int $width): void
{
$this->width = $this->height = $width;
}
public function setHeight(int $height): void
{
$this->width = $this->height = $height;
}
}
function printArea(Rectangle $rectangle): void
{
$rectangle->setWidth(4);
$rectangle->setHeight(5);
// BAD: Will return 25 for Square. Should be 20.
echo sprintf('%s has area %d.', get_class($rectangle), $rectangle->getArea()).PHP_EOL;
}
$rectangles = [new Rectangle(), new Square()];
foreach ($rectangles as $rectangle) {
printArea($rectangle);
}
|
好的
最好是将这两种四边形分别对待,用一个适合两种类型的更通用子类型来代替。
尽管正方形和长方形看起来很相似,但他们是不同的。 正方形更接近菱形,而长方形更接近平行四边形。但他们不是子类型。 尽管相似,正方形、长方形、菱形、平行四边形都是有自己属性的不同形状。
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
|
interface Shape
{
public function getArea(): int;
}
class Rectangle implements Shape
{
private $width = 0;
private $height = 0;
public function __construct(int $width, int $height)
{
$this->width = $width;
$this->height = $height;
}
public function getArea(): int
{
return $this->width * $this->height;
}
}
class Square implements Shape
{
private $length = 0;
public function __construct(int $length)
{
$this->length = $length;
}
public function getArea(): int
{
return $this->length ** 2;
}
}
function printArea(Shape $shape): void
{
echo sprintf('%s has area %d.', get_class($shape), $shape->getArea()).PHP_EOL;
}
$shapes = [new Rectangle(4, 5), new Square(5)];
foreach ($shapes as $shape) {
printArea($shape);
}
|
I: 接口隔离原则 (ISP) Interface Segregation Principle
接口隔离原则表示:”调用方不应该被强制依赖于他不需要的接口”
有一个清晰的例子来说明示范这条原则。当一个类需要一个大量的设置项, 为了方便不会要求调用方去设置大量的选项,因为在通常他们不需要所有的 设置项。使设置项可选有助于我们避免产生”胖接口”
坏
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
|
interface Employee
{
public function work(): void;
public function eat(): void;
}
class HumanEmployee implements Employee
{
public function work(): void
{
// ....working
}
public function eat(): void
{
// ...... eating in lunch break
}
}
class RobotEmployee implements Employee
{
public function work(): void
{
//.... working much more
}
public function eat(): void
{
//.... robot can't eat, but it must implement this method
}
}
|
好
不是每一个工人都是雇员,但是每一个雇员都是一个工人
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
|
interface Workable
{
public function work(): void;
}
interface Feedable
{
public function eat(): void;
}
interface Employee extends Feedable, Workable
{
}
class HumanEmployee implements Employee
{
public function work(): void
{
// ....working
}
public function eat(): void
{
//.... eating in lunch break
}
}
// robot can only work
class RobotEmployee implements Workable
{
public function work(): void
{
// ....working
}
}
|
D: 依赖倒置原则 (DIP) Dependency Inversion Principle
这条原则说明两个基本的要点:
- 高阶的模块不应该依赖低阶的模块,它们都应该依赖于抽象
- 抽象不应该依赖于实现,实现应该依赖于抽象
这条起初看起来有点晦涩难懂,但是如果你使用过 PHP 框架(例如 Symfony),你应该见过 依赖注入(DI),它是对这个概念的实现。虽然它们不是完全相等的概念,依赖倒置原则使高阶模块 与低阶模块的实现细节和创建分离。可以使用依赖注入(DI)这种方式来实现它。最大的好处 是它使模块之间解耦。耦合会导致你难于重构,它是一种非常糟糕的的开发模式。
坏的
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
|
class Employee
{
public function work(): void
{
// ....working
}
}
class Robot extends Employee
{
public function work(): void
{
//.... working much more
}
}
class Manager
{
private $employee;
public function __construct(Employee $employee)
{
$this->employee = $employee;
}
public function manage(): void
{
$this->employee->work();
}
}
|
好的
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
|
interface Employee
{
public function work(): void;
}
class Human implements Employee
{
public function work(): void
{
// ....working
}
}
class Robot implements Employee
{
public function work(): void
{
//.... working much more
}
}
class Manager
{
private $employee;
public function __construct(Employee $employee)
{
$this->employee = $employee;
}
public function manage(): void
{
$this->employee->work();
}
}
|
设计模式 Design Patterns
以下列出这么多设计模式并不见到都要一一掌握,相信很多人在日常的开发中也自觉不自觉的用到不少设计模式,这篇文章更系统的讲了所有设计模式的适用场景并配有例子,通读一遍还是有意义的,常见的10多种掌握就可以了
- 创建型
- 抽象工厂模式(Abstract Factory)
- 建造者模式(Builder)
- 工厂方法模式(Factory Method)
- 多例模式(Multiton)
- 对象池模式(Pool)
- 原型模式(Prototype)
- 简单工厂模式(Simple Factory)
- 单例模式(Singleton)
- 静态工厂模式(Static Factory)
- 结构型
- 适配器模式(Adapter)
- 桥梁模式(Bridge)
- 组合模式(Composite)
- 数据映射模式(Data Mapper)
- 装饰模式(Decorator)
- 依赖注入模式(Dependency Injection)
- 门面模式(Facade)
- 流接口模式(Fluent Interface)
- 享元模式(Flyweight)
- 代理模式(Proxy)
- 注册模式(Registry)
- 行为型
- 责任链模式(Chain Of Responsibilities)
- 命令行模式(Command)
- 迭代器模式(Iterator)
- 中介者模式(Mediator)
- 备忘录模式(Memento)
- 空对象模式(Null Object)
- 观察者模式(Observer)
- 规格模式(Specification)
- 状态模式(State)
- 策略模式(Strategy)
- 模板方法模式(Template Method)
- 访问者模式(Visitor)
- 更多模式
- 委托模式(Delegation)
- 服务定位器模式(Service Locator)
- 资源库模式(Repository)
- 实体属性值模式(EAV 模式)
其他学习资料
后记
本文内容纯搬运,后续我会加入一些自己的理解讲几个比较实用的设计模式,敬请期待!