热度

Design

设计模式

TODO: 设计模式

创造型设计模式

  • 简单工厂
  • 工厂方法
  • 抽象工厂
  • 构建器
  • 原型
  • 单例

结构型设计模式

  • 适配器
  • 桥梁
  • 组合
  • 装饰
  • 门面
  • 享元
  • 代理

行为型设计模式

  • 责任链
  • 命令行
  • 迭代器
  • 中介者
  • 备忘录
  • 观察者
  • 访问者
  • 策略
  • 状态
  • 模版方法

设计模式

创造型 结构型 行为型

创造型设计模式

  • 简单工厂:

    只是为客户端生成一个实例,而不会向客户端公开任何实例化逻辑
    工厂时用户创建其他对象的对象,正式工厂是一种函数或方法,它从一些方法调用返回变化的原型或类的对象,这被假定为"新"

    程序化示例:
    首先,定义一个门界面和实现

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    interface Door {
    public function getWidth(): float;
    public function getHeight(): float;
    }

    clas WoodenDoor implements Door {
    protected $width;
    protected $height;

    public function __construct(float $width, float $height) {
    $this -> width = $width;
    $this -> height = $height;
    }

    public function getWidth(): float {
    return $this -> width;
    }

    public function getHeight(): float {
    return $this -> height;
    }
    }

    我们有我们的门工厂、门,并返回它

    1
    2
    3
    4
    5
    class DoorFactory {
    public static function makeDoor($width, $height): Door {
    return new WoodenDoor($width, $height);
    }
    }

    然后它可以用作

    1
    2
    3
    4
    5
    6
    7
    8
    // Make me a door of 300 x 300
    $door = DoorFactory::makeDoor(300,300);

    echo 'Width: ' . $door -> getWidth();
    echo 'Height: '. $door -> getHeight();

    // Make me a door of 100 x 100
    $door2 = DoorFactory::makeDoor(100,100);

用处:当创建一个对象不仅仅是一些分配而且涉及一些逻辑时,将它放在专用工厂中,而不是在任何地方重复相同的代码时有意义的

  • 工厂方法
    提供了一种将实例化逻辑委托给子类的方法
    处理创建对象的问题,无需指定将要创建的对象的确切类。在接口中指定并由子类实现,或者在基类中实现并可选地由派生类覆盖,而不是通过调用构造函数
    程序化示例:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    interface Interviewer {
    public function askQuestions();
    }

    class Developer implements Interviewer {
    public function askQuestions() {
    echo 'Factory Design Patterns ';
    }
    }

    class CommunityExecutive implements Interviewer {
    public function askQuestions() {
    echo 'Asking about community building ';
    }
    }

    创造 HiringManager

    1
    2
    3
    4
    5
    6
    7
    8
    9
    abstract class HiringManager {
    // Factory method
    abstract protected function makeInterviewer(): Interviewer;

    public function takeInterview() {
    $interviewer = $this -> makeInterviewer();
    $interviewer -> askQuestions();
    }
    }

任何子类可以延长并提供所需的

1
2
3
4
5
6
7
8
9
10
11
class DevelopmentManager extends HiringManager {
protected function makeInterviewer(): Interviewer {
return new Developer();
}
}

class MarketingManager extends HiringManager {
protected function makeInterviewer(): Interviewer {
return new CommunityExecutive();
}
}
1
2
3
4
5
$devManager = new DevelopmentManager();
$devManager -> takeInterview(); // Output: Asking about design patterns

$marketingManager = new MarketingManager();
$marketingManager -> takeInterview(); // Output : Asking about community building

用处:
在类中有一些通用处理但在运行时动态决定所需的子类时用,当客户端不知道他需要什么样子的子类时

  • 抽象工厂
    将个人 相关\依赖工厂组在一起而不指定其具体类别的工厂
    提供了一种封装一组具有共同主题但没有指定具体类的单个工厂的方法
    程序化示例
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    interface Door {
    public function getDescription();
    }

    class WooderDoor implements Door {
    public function getDescription() {
    echo 'I am a wooden door';
    }
    }

    class IronDoor implements Door {
    public function getDescription() {
    echo 'I am an iron door';
    }
    }

为每种门类型都配备一些装配专家

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
interface DoorFittingExpert {
public function getDescription();
}

class Weler implements DoorFittingExpert {
public function getDescription() {
echo 'i can only fit iron doors ';
}
}

class Carpenter implements DoorFittingExpert {
public function getDescription() {
echo 'I can only fit wooden doors ';
}
}

有抽象工厂,制作相关对象的家庭,即木门工厂将创建一个木门和木门配件,门专家

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
interface DoorFactory {
public function makeDoor(): Door;
public function makeFittingExpert(): DoorFittingExpert;
}

// Wooden factory to return carpenter and wooden door
class WoodenDoorFactory implements DoorFactory {
public function makeDoor(): Door {
return new WoodenDoor();
}

public function makeFittingExpert(): DoorFittingExpert {
return new Carpenter();
}
}

// Iron Door factory to get iron door and the relevant fitting expert
class IronDoorFactory implements DoorFactory {
public function makeDoor(): Door {
return new IronDoor();
}

public function makeFittingExpert(): DoorFittingExpert {
return new Welder();
}
}

// Iron d

可用作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$woodenFactory = new WoodenDoorFactory();

$door = $woodenFactory -> makeDoor();
$expert = $woodenFactory -> makeFittingExpert();

$door -> getDescription(); // Output: i am a wooden door
$expert -> getDescription();

// Same for Iron Factory
$ironFactory = new IronDoorFactory();

$door = $ironFactory -> makeDoor();
$expert = $ironFactory -> makeFittingExpert();

$door -> getDescription();
$expert -> getDescription();

木门工厂疯转 各种函数
用法: 当存在互相关联的依赖关系时,涉及非简单的创建逻辑

  • 构建器
    允许创建不同风格的对象,同时避免构造函数污染,当有几种风格的物体时很有用,或在创建对象时设计很多步骤
    目的:找到伸缩构造器反模式的解决方案
    程序化示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    class Burger {
    protected $size;

    protected $cheese = false;
    protected $pepperoni = false;
    protected $lettuce = false;
    protected $tomato = false;

    public function __construct(BurgerBuilder $builder) {
    $this -> size = $builder -> size;
    $this -> cheese = $builder -> cheese;
    $this -> pepperoni = $builder -> pepperoni;
    $this -> lettuce = $builder -> lettuce;
    $this -> tomato = $builder -> tomato;
    }
    }

然后有建设者

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
class BurgerBuilder {
public $size;

public $cheese = false;
public $pepperoni = false;
public $lettuce = false;
public $tomato = false;

public function __construct(int $size) {
$this -> size = $size;
}

public function addPepperoni() {
$this -> pepperoni = true;
return $this;
}

public function addLettuce() {
$this -> lettuce = true;
return $this;
}

public function addCheese() {
$this -> cheese = true;
return $this;
}

public function addTomato() {
$this -> tomato = true;
return $this;
}

public function build(): Burger {
return new Burger($this);
}
}

用法:

1
2
3
4
5
$burger = (new BurgerBuilder(14)) 
-> addPepperoni()
-> addLettuce()
-> addTomato()
-> build();

用处:
当可能存在几种类型的对象并避免构造函数伸缩时,与工厂模式区别在于:当创建时一步过程时,将使用工厂模式,而当创建是多步骤过程时,将使用构造器模式

  • 原型
    通过克隆基于现有对象创建对象, 允许创建现有对象的副本并进行修改,而不是从头开始创建对象并进行设置
    程序化示例
    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
    class Sheep {
    protected $name;
    protected $category;

    public function __construct(string $name, string $category = 'Mountain Sheep') {
    $this -> name = $name;
    $this -> category = $category;
    }

    public function setName(string $name) {
    $this -> name = $name;
    }

    public function getName() {
    return $this -> name;
    }

    public function setCategory(string $category) {
    $this -> category = $category;
    }

    public function getCategory() {
    return $this -> category;
    }
    }

用法:

1
2
3
4
5
6
7
8
9
$original = new Sheep('Hale');
echo $original -> getName(); // Hale
echo $original -> getCategory() // Mountain Sheep

// Clone and Modify what is required
$cloned = clone $original;
$cloned -> setName('Lv');
echo $cloned -> getName(); // Lv
echo $cloned -> getCategory(); // Mountain Sheep

可用魔术方法 __clone() 来修改克隆方法
用处: 当需要一个与现有对象类似的对象时,或者与克隆相比,创建的成本会很高

  • 单例
    确保只创建特定类的一个对象
    程序化示例
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    final Class President {
    private static $instance;

    private function __construct() {
    // Hide the constructor
    }

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

    private function __clone() {
    // Disable cloning
    }

    private function __wakeup() {
    // Disable unserialize
    }
    }

用法:

1
2
3
4
$president1 = President::getInstance();
$president2 = President::getInstance();

var_dump($president1 === $president2); // true

结构型设计模式

适配器 桥梁 组合 装饰 门面 享元 代理

适配器:
在适配器中包装其他不兼容的对象,以使其与另一个类兼容。 允许将现有类的接口用作另一个接口,通常用于使现有类与其他类一起工作而无需修改其源代码
程序化示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
interface Lion {
public function roar();
}

class AfricanLion implements Lion {
public function roar(){

}
}

class AsianLion implements Lion {
public function roar(){

}
}

实现任何Lion接口可以进行搜索

1
2
3
4
5
class Hunter {
public function hunt(Lion $lion) {
$lion -> roar();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
class Wilddog {
public function bark() {

}
}

// Adapter around wild dog to make it compatible with our game
class WildDogAdapter implements Lion {
protected $dog;
public function __construct(WildDog $dog) {
$this -> dog = $dog;
}
}
1
2
3
4
5
$wildDog = new WildDog();
$wildDogAdapter = new WildDogAdapter($wildDog);

$hunter = new Hunter();
$hunter -> hunt($wildDogAdapter);

桥梁模式
优先于集成的组合,实现细节从层次结构推送到具有单独层次结构的另一个对象
程序化示例

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
interface WebPage {
public function __construct(Theme $theme);
public function getContent();
}

class About implements WebPage {
protected $theme;

public function __construct(Theme $theme) {
$this -> theme = $theme;
}

public function getContent() {
return 'About page in' . $this -> theme -> getColor();
}
}

class Careers implements WebPage {
protected $theme;

public function __construct(Theme $theme) {
$this -> theme = $theme;
}

public function getContent() {
return 'Careers page in ' . $this -> theme -> getColor();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
interface Theme {
public function getColor();
}

class DarkTheme implements Theme {
public function getColor() {
return 'Dark Black';
}
}

class LightTheme implements Theme {
public function getColor() {
return 'Off white';
}
}

class AquaTheme implements Theme {
public function getColor() {
return 'Light theme';
}
}
1
2
3
4
5
6
7
$darkTheme = new DarkTheme();

$about = new About($darkTheme);
$careers = new Careers($darkTheme);

echo $about -> getContent(); // about page in dark black
echo $careers -> getContent(); // Careers page in Dark Black

组合模式
复合模式允许客户以统一的方式处理单个对象
程序化示例

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
interface Employee {
public function __construct(string $name , float $salary);
public function getName(): string;
public function setSalary(float $salary);
public function getSalary(): flaot;
public function getRoles(): array;
}

class Developer implements Employee {
protected $salary;
protected $name;
protected $roles;

public function __construct(string $name, float $salary) {
$this -> name = $name;
$this -> salary = $salary;
}

public function getName(): string {
return $this -> name;
}

public function setSalary(float $salary) {
$this -> salary = $salary;
}

public function getSalary(): float {
return $this -> salary;
}

public function getRoles(): array {
return $this -> roles;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Organization {
protected $employees;

public function addEmployee(Employee $employee) {
$this -> employees[] = $employee;
}

public function getNetSalaries(): float {
$netSalary = 0;

foreach($this -> employees as $emploess) {
$netSalary += $employee -> getSalary();
}
return $netSalary;
}
}
1
2
3
4
5
6
7
8
9
$john = new Developer('John Doe', 12000);
$hale = new Designer('Hale Lv', 15000);

// Add them to organization()
$organization = new Organization();
$organization -> addEmployee($john);
$organization -> addEmployee($hale);

echo 'Net Salaries: ' . $organization -> getNetSalaries(); // Net Salaries : 27000

装饰模式
通过将对象包装在装饰器类的对象中来动态更改对象在运动时的行为
程序化示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
interface Coffee {
public function getCost();
public function getDescription();
}

class SimpleCoffee implements Coffee {
public function getCost() {
return 10;
}

public function getDescription() {
return 'Simple Coffee';
}
}

添加组件

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
class MilkCoffee implements Coffee {
protected $coffee;

public function __constrcut(Coffee $coffee) {
$this -> coffee = $coffee;
}

public function getCost() {
return $this -> coffee -> getCost + 2;
}

public function getDescription() {
return $this -> coffee -> getDescription() . ' Milk ';
}
}

class WhipCoffee implements Coffee {
protected $coffee;

public function __construct(Coffee $coffee) {
$this -> coffee = $coffee;
}

public function getCost() {
return $this -> coffee -> getCost() + 5;
}

public function getDescription() {
return $this -> coffee -> getDescription() . 'whip';
}
}

class VanlillaCoffee implements Coffee {
protected $coffee;

public function __constrcut(Coffee $coffee) {
$this -> coffee = $coffee;
}

public function getCost() {
return $this -> coffee = getCost() + 3;
}

public function getDescription() {
return $this -. coffee -> getDescription(). ' Valilla';
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$someCoffee = new SimpleCoffee();
echo $someCoffee -> getCost();
echo $someCoffee -> getDescription();

$someCoffee = new MilkCoffee($someCoffee);
echo $someCoffee -> getCost();
echo $someCoffee -> getDescription();

$someCoffee = new WhipCoffee($someCoffee);
echo $someCoffee -> getCost();
echo $someCoffee -> getDescription();

$someCoffee = new VanillaCoffee($someCoffee);
echo $someCoffee -> getCost();
echo $someCoffee -> getDescription();

门面模式

Facade 模式为复杂的子系统提供了简化的界面
外观是一个对象,它为更大的代码提供了简化的接口,如类库
程序化示例
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
class Computer {
public function getElectricShock() {
echo 'CDB';
}

public function makeSound() {
echo 'Liunx';
}

public function showLoadingScreen() {
echo 'Loding ... ';
}

public function bam() {
echo 'Ready to be used !';
}

public function closeEverything() {
echo 'Biu biu biu ... !';
}

public function sooth() {
echo 'zzzzz';
}

public function pullCurrent() {
echo 'Hahaha!';
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class ComputerFacade {
protected $computer;

pulic function __construct(Computer $computer) {
$this -> computer = $computer;
}

public function turnOn() {
$this -> computer -> getElectricShock();
$this -> computer -> makeSound();
$this -> computer -> showLoadingScreen();
$this -> computer -> bam();
}

public function turnOff() {
$this -> computer -> closeEverything();
$this -> computer -> pullCurrent();
$this -> computer -> sooth();
}
}
1
2
3
$computer = new ComputerFacade(new Computer());
$computer -> turnOn();
$computer -> turnOff();

享元模式
通过尽可能多地与类似对象共享来最小化内存使用或计算开销
程序示例

1
2
3
4
5
6
7
8
9
10
11
12
class KarakTea {}

class TeaMaker {
protected $availableTea = [];

public function make($preference) {
if(empty($this -> availableTea[$preference])) {
$this -> availableTea[$preference] = new KarakTea();
}
return $this -> availableTea[$preference];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class TeaShop {
protected $orders;
protected $teaMaker;

public function __construct(TeaMaker $teaMaker) {
$this -> teaMaker = $teaMaker;
}

public function takeOrder(string $teaType, int $table) {
$this -> orders[$table] = $this -> teaMaker -> make(teaType);
}

public function serve() {
foreach($this -> orders as $table => $tea) {
echo 'Serving tea to table ' . $table;
}
}
}
1
2
3
4
5
6
7
8
$teaMaker = new TeaMaker();
$shop = new TeaShop($teaMaker);

$shop -> takeOrder('Less Sugar');
$shop -> takeOrder('More Milk');
$shop -> takeOrder('Without Sugar', 5);

$shop -> serve();

代理模式
类表示另一个类的功能
程序化示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
interface Door {
public function open();
public function close();
}

class LabDoor implements Door {
public function open() {
echo 'Opening lab door';
}

public function close() {
echo 'Closing the lab door';
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class SecuredDoor {
protected $door;

public function __constrcut(Door $door) {
$this -> door = $door;
}

public function open($password) {
if($this -> authenticate($password)) {
$this -> door -> open();
}else {
echo 'Big no! ';
}
}

public function authenticate($password) {
return $password === '$ecr@t';
}

public function close() {
$this -> door -> close();
}
}

用法:

1
2
3
4
5
$door = new SecureDoor(new LabDoor());
$door -> open('invalid');

$door -> open('$ecr@t');
$door -> close();

行为型设计模式

责任链 命令行 迭代器 中介者 备忘录 观察者 访问者 策略 状态 模板

责任链
构建一系列对象,请求从一端进入并继续从一个对象到另一个对象,直到找到合适的处理程序
程序示例

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
abstract class Account {
protected $successor;
protected $balance;

public function setNext(Account $account) {
$this -> succcessor = $account;
}

public function par(float $amountToPay) {
if($this -> canPay($amountToPay)) {
echo sprintf('Paid %s using %s ' . PHP_EOL, $amountToPay, get_called_class());
}else if($this -> successor) {
echo sprintf('Cannot pay using %s. Proceeding..' .PHP_EOL, get_called_class());
$this -> successor -> pay($amountToPay);
}else {
throw new Exception('None of the accounts have enough balance');
}
}

public function canPay($amount): bool {
return $this -> balance >= $amount; // 原文是 >= ,感觉应该是 =
}
}

class Bank extends Account {
protected $balance;

public function __construct(float $balance) {
$this -> balance = $balance;
}
}

class Bitcoin extends Account {
protected $balance;

public function __constrcut(flaot $balance) {
$this -> balance = $balance;
}
}
1
2
3
4
5
6
7
8
$bank = new Bank(100);
$paypal = new Paypal(200);
$bitcoin = new Bitcoin(300);

$bank -> setNext($paypal);
$paypal -> setNext($bitcoin);

$bank -> pay(259);

命令行
将操作封装在对象中,提供将客户与接收器分离的方法. 对象用于封装执行动作或稍后触发事件所需的所有信息,此信息包括方法名称,拥有该方法的对象以及方法参数的值。
程序化示例

1
2
3
4
5
6
7
8
9
class Bulb {
public function trunOn() {
echo 'Buld has been lit';
}

public function turnOff() {
echo 'Darkness !';
}
}
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 Command {
public function execute();
public function undo();
public function redo();
}

class TurnOn implements Command {
protected $bulb;

public function __construct(Bulb $bulb) {
$this -> bulb = $bulb;
}

public function execute() {
$this -> bulb -> turnOn();
}

public function undo() {
$this -> bulb -> turnOff();
}

public function redo() {
$this -> execute();
}
}

class TurnOff implements Command {
protected $bulb;

public function __constrcut(Bulb $bulb) {
$this -> bulb = $bulb;
}

public function execute() {
$this -> bulb -> turnOff();
}

public function undo() {
$this -> bulb -> turnOn();
}

public function redo() {
$this -> execute();
}
}
1
2
3
4
5
class RemoteControl {
public function submit(Command $command) {
$command -> execute();
}
}
1
2
3
4
5
6
7
8
$bulb = new Bulb();

$turnOn = new TurnOn($bulb);
$turnOff = new TurnOff($bulb);

$remote = new RemoteControl();
$remote -> submit($turnOn);
$remote -> submit($turnOff);

迭代器
提供了一种访问对象元素而不是暴露底层表示的方法
用于遍历容器并访问容器的元素,将算法与容器分离,因算法是特定于容器,so 不能解耦
程序化示例

1
2
3
4
5
6
7
8
9
10
11
class RadioStation {
protected $frequency;

public function __construct(float $frequency) {
$this -> frequency = $frequency;
}

public function getFrequency(): float {
return $this -> frequency;
}
}
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
use Countable;
use Iterator;

class StationList implements Countable, Iterator {
protected $stations = [];
protected $counter = [];

public function addStation(RadioStation $station) {
$this -> stations[] = $station;
}

public function removeStation(RadioStation $toRemove) {
$toRemoveFrequency = $toRemove -> getFrequency();
$this -> stations = array_filter($this -> stations, function(RadioStation $station) use ($toRemoveFrequency) {
return $station -> getFrequency() !== $toRemoveFrequency;
});
}

public function count(): int {
return count($this -> stations);
}

public function current(): RadioStation {
return $this -> stations[$this -> counter];
}

public function key() {
return $this -> counter;
}

public function next(){
$this -> counter++;
}

public function rewind() {
$this -> counter = 0;
}

public function valid(): bool {
return isset($this -> stations[$this -> counter]);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
$stationList = new StationList();

$stationList -> addStation(new RadioStation(89));
$stationList -> addStation(new RadioStation(90));
$stationList -> addStation(new RadioStation(100));
$stationList -> addStation(new RadioStation(120.3));

foreach($stationList as $station) {
echo $station -> getFrequency() . PHP_EOL;
}

$stationList -> removeStation(new RadioStation(89));

中介者
添加第三方对象控制两个对象之间的交互,减少彼此通信的类之间的耦合,不需要了解彼此的实施。 中介模式定义了一个对象,该对象封装了一组对象的交互方式,可以改变程序的运行行为。
程序化示例

1
2
3
4
5
6
7
8
9
10
11
12
interface ChatRoomMediator {
public function showMessage(User $user, string $message);
}

class CharRoom implements CharRoomMediator {
public function showMessage(User $user, string $message) {
$time = date('M d, y H:i');
$sender = $user -> getName();

echo $time . '[' . $sender .']:' . $message;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class User {
protected $name;
protected $charMediator;

public function __constrcut(string $name, ChatRoomMediator $chatMediator) {
$this -> name = $name;
$this -> chatMediator = $chatMediator;
}

public function getName() {
return $this -> name;
}

public function send($message) {
$this -> chatMediator -> showMessage($this, $message);
}
}
1
2
3
4
5
6
7
$mediator = new ChatRoom();

$hale = new User('Hale Lv ', $mediator);
$judy = new User('Judy ', $mediator);

$hale -> send('Hi there!');
$judy -> send('Hey!!!');

本文标题:Design

文章作者:

Hale Lv

发布时间:2019年08月14日 - 23:08

最后更新:2019年08月15日 - 20:08

原始链接:http://yoursite.com/2019/08/14/Design-Note/

许可协议: 转载请保留原文链接及作者。

<center> Hale Lv </center> wechat
扫一扫,公众号!
文能提笔安天下,武能上马定乾坤!
-------------本文结束感谢您的阅读-------------