6.装饰器模式
理解:达到动态修改类方法的目的,比如模板文字,我想把他改成红色的。
与观察者模式类似,观察者模式是将观察者在事件发生的时候注册到事件类中,并且发送给所有观察者
装饰器是将要在装饰的时候,在触发类里面注册装饰器已经前置 后置操作
class Template{
protected $decorator;
public function index(){
$this->before();
echo '我是一个模板';
$this->after();
}
public function addDecorator(decorator $decorator){
$this->decorator[] = $decorator;
}
protected function before(){
if(empty($this->decorator)) return;
foreach ($this->decorator as $dec){
$dec->before();
}
}
protected function after(){
if(empty($this->decorator)) return;
$this->decorator = array_reverse($this->decorator);
foreach ($this->decorator as $dec){
$dec->after();
}
}
}
interface Decorator{
public function before();
public function after();
}
class Color implements Decorator{
protected $color;
public function __construct($color)
{
$this->color = $color;
}
public function before()
{
echo "<dis style='color: {$this->color}'>";
}
public function after()
{
echo "</div>";
}
}
class Size implements Decorator{
protected $size;
public function __construct($size)
{
$this->size = $size;
}
public function before()
{
echo "<dis style='font-size: {$this->size}'>";
}
public function after()
{
echo "</div>";
}
}
$temp = new Template();
$temp->index();
echo '<br/>';
$temp->addDecorator(new Color('red'));
$temp->addDecorator(new Size('20px'));
$temp->index();
7.代理模式
理解:在客户端和实体之间,建立一个代理对象(proxy),客户端对实体进行的操作,全部委派给代理对象,隐藏实体的具体实现细节。
interface User{
public function getName();
public function getAge();
}
class Getinfo implements User{
public function getName()
{
echo '我的名字叫张三<br>';
}
public function getAge()
{
echo '我今年18岁了';
}
}
class Porxy implements User{
protected $real;
public function __construct(Getinfo $real)
{
$this->real = $real;
}
public function getName()
{
$this->real->getName();
}
public function getAge()
{
$this->real->getAge();
}
}
$porxy = new Porxy(new Getinfo());
$porxy->getName();
$porxy->getAge();