装饰者模式
<?php
interface Decorator
{
public function display();
}
class XiaoFang implements Decorator
{
private $name;
public function __construct($name)
{
$this->name = $name;
}
public function display()
{
echo "我是".$this->name."我出门了!!!".'<br>';
}
}
class Finery implements Decorator
{
private $component;
public function __construct(Decorator $component)
{
$this->component = $component;
}
public function display()
{
$this->component->display();
}
}
class Shoes extends Finery
{
public function display()
{
echo "穿上鞋子".'<br>';
parent::display();
}
}
class Skirt extends Finery
{
public function display()
{
echo "穿上衣服".'<br>';
parent::display();
}
}
class Fire extends Finery
{
public function display()
{
echo "出门前先整理头发".'<br>';
parent::display();
echo '出门后再整理一下头发'.'<br>';
}
}
$xiaofang = new XiaoFang('小芳');
$shoes = new Shoes($xiaofang);
$skirt = new Skirt($shoes);
$fire = new Fire($skirt);
$fire->display();
观察者模式
<?php
abstract class EventGenerator
{
private $observers = [];
public function add(Observer $observer)
{
$this->observers[] = $observer;
}
public function notify()
{
foreach ($this->observers as $observer) {
$observer->update();
}
}
}
interface Observer
{
public function update($eventInfo = null);
}
class Li implements Observer
{
public function update($eventInfo = null)
{
echo '观察者小李,收到通知,执行完毕!\n';
}
}
class Wang implements Observer
{
public function update($eventInfo = null)
{
echo '观察者小王,收到通知,执行完毕!\n';
}
}
class Event extends EventGenerator
{
public function trigger()
{
$this->notify();
}
}
$event = new Event();
$event->add(new Li());
$event->add(new Wang());
$event->trigger();