PHP中常用设计模式记录

单例模式

  • 不通过构造方法获取实例
  • 有一个静态属性保存自身
  • 暴露一个公共方法来获取实例(判断是否有实例,没有就new,有就直接返回)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class SingleTon {
private static $instance;

private function __construct()
{
}

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


}

工厂模式

  • 通过不同的参数来返回不同的对象实例
  • 被返回的实例通常是同一功能的不同实现
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
interface Login {
function verify();
}

require_once './IFactory.php';
class PasswordLogin implements Login {

public function verify() {
// 密码登录
}
}

require_once './DomainLogin.php';
require_once './PasswordLogin.php';

class LoginFactory {

public static function getLoginFactory($type) {
if($type == 'domain') {
return new DomainLogin();
}else if($type == 'pass') {
return new PasswordLogin();
}else {
throw new Exception('class not found');
}
}
}

require_once './IFactory.php';

class DomainLogin implements Login {
public function verify()
{
// 域名验证登录
}
}

命令链模式以松散耦合主题为基础,发送消息、命令和请求,或通过一组处理程序发送任意内容。

  • 每个处理程序都会自行判断自己能否处理请求。如果可以,该请求被处理,进程停止。
  • 我们可以为系统添加或移除处理程序,而不影响其他处理程序。
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
interface ICommand {
function onCommand($name, $args);
}

class CommandChain {
private $_commands = [];

public function addCommand($cmd) {
$this->_commands = $cmd;
}

public function runCommand($name, $args) {
foreach($this->_commands as $command) {
if($command->onCommand($name, $args)) {
return;
}
}
}
}

class UserCommand implements ICommand {
public function onCommand($name, $args)
{
if($name != 'addUser')
return false;
echo "user handind! \n";
return true;
}
}

class MailCommond implements ICommand {
public function onCommand($name, $args)
{
if($name != 'addMail')
return false;
echo "mail handind! \n";
return true;
}
}

$chain = new CommandChain();
$chain->addCommand(new UserCommand());
$chain->addCommand(new MailCommond());
$chain->runCommand('addUser', null);
$chain->runCommand('addMail', null);

观察者模式:

  • 一个对象通过添加一个方法(该方法允许另一个对象,即观察者 注册自己)使本身变得可观察。
  • 当可观察的对象更改时,它会将消息发送到已注册的观察者。这些观察者使用该信息执行的操作与可观察的对象无关。
  • 结果是对象可以相互对话,而不必了解原因。
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
interface IObserver {
function onChange($sender, $args);
}

interface IObservable {
function addObserver($observer);
}

class UserList implements IObservable {
private $_obervers = [];

public function addCustomer($name) {
foreach($this->_obervers as $oberver) {
$oberver->onChange($this, $name);
}
}

public function addObserver($observers)
{
$this->_obervers = $observers;
}
}

class UserListLogger implements IObserver {
public function onChange($sender, $args)
{
echo "{$args} added to user list \n";
}
}

$ul = new UserList();
$ul->addObserver(new UserListLogger());
$ul->addCustomer("haobin");
坚持原创技术分享,您的支持将鼓励我继续创作!