设计模式 状态模式

WechatIMG11.jpeg

介绍

状态模式是一种行为型设计模式,它允许对象在其内部状态发生改变时改变其行为。状态模式将对象的不同状态封装成不同的类,从而可以动态地改变对象的行为。

角色

角色 说明
Context 环境类,维护一个 ConcreteState 子类的实例,这个实例定义当前状态
State 抽象状态类,定义一个接口以封装与 Context 的一个特定状态相关的行为
ConcreteState 具体状态类,每一个子类实现一个与 Context 的一个状态相关的行为

角色示例

类名 担任角色 说明
Vip 环境类 会员类
Level 抽象状态类 会员等级类
Level1 具体状态类 等级一
Level2 具体状态类 等级二
Level3 具体状态类 等级三

UML类图

状态模式.png

代码

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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php 
class Vip{
protected $level;

protected static $money = 0;

function __construct()
{
$this->level = Level1::getInstance();
}

public function changeLevel()
{
$money = $this->money;
switch ($money) {
case ($money >= 0 && $money < 5):
$this->level = Level1::getInstance();
break;
case ($money >= 5 && $money < 10):
$this->level = Level2::getInstance();
break;
case ($money >= 10):
$this->level = Level3::getInstance();
break;
}
return '变更'.get_class($this->level).PHP_EOL;
}

public function deposit($money)
{
$this->money += $money;
return '充值'.$money.',余额'.$this->money.','.$this->level->check($this);
}
}

abstract class Level{

abstract function check(Vip $vip);

}


class Level1 extends Level
{
private static $instance;

private function __construct(){}

private function __clone(){}

public static function getInstance()
{
if (!isset(self::$instance)) {
self::$instance = new self;
}
return self::$instance;
}

public function check(Vip $vip)
{
return $vip->changeLevel();
}
}

class Level2 extends Level
{
private static $instance;

private function __construct(){}

private function __clone(){}

public static function getInstance()
{
if (!isset(self::$instance)) {
self::$instance = new self;
}
return self::$instance;
}

public function check(Vip $vip)
{
return $vip->changeLevel();
}
}

class Level3 extends Level
{
private static $instance;

private function __construct(){}

private function __clone(){}

public static function getInstance()
{
if (!isset(self::$instance)) {
self::$instance = new self;
}
return self::$instance;
}

public function check(Vip $vip)
{
return $vip->changeLevel();
}
}

$vip = new Vip();
echo $vip->deposit(3);
echo $vip->deposit(6);
echo $vip->deposit(9);

创建 Vip.php,内容如上。

执行

1
2
3
4
$ php Vip.php
充值3,余额3,变更Level1
充值6,余额9,变更Level2
充值9,余额18,变更Level3
-------------本文结束感谢您的阅读-------------
0%