PHP设计模式 五 (代理模式 装饰器模式)

代理模式

在客户端和实体之间建立一个代理对象,客户端对实体的操作全部委派给代理对象,隐藏实体具体实现细节。Proxy还可以与业务代码分离,部署到另外的服务器,业务代码中通过RPC来委派任务。代理Proxy.php:

<?phpnamespace Components\Proxy;class Proxy implements IUserProxy {function get($id) {$db = \Components\Register::get('slave');$db->query('select name from users where id ='.$id);}function set($id, $name) {$db = \Components\Register::get('master');$db->query("update users set name=$name where id =$id");}}IUserProxy.php:<?phpnamespace Components\Proxy;interface IUserProxy {function get();function set();}调用:/* 代理模式 适用于类似主从 */$proxy = new Proxy();$proxy->get('1');$proxy->set('1', 'php');

装饰器模式

在不必改变原类文件和使用继承的情况下,,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。装饰器接口IDecorator.php:

<?phpnamespace Components\Decorator;/** * 装饰器模式 接口 * @author WH * */interface IDecorator {function before();function after();}装饰器1DecoratorAttr1.php:<?phpnamespace Components\Decorator;class DecoratorAttr1 implements IDecorator{function before() {echo '<br><div style="color:red">';}function after() {echo '</div>';}}装饰器2 DecoratorAttr2.php:<?phpnamespace Components\Decorator;class DecoratorAttr2 implements IDecorator{function before() {echo '<br><div style="font-size:30px">';}function after() {echo '</div>';}}使用:/* 装饰器模式 原类 */class DecoratorClassTest {protected $decorators = array();//添加装饰器function addDecorator(\Components\Decorator\IDecorator $decorator) {$this->decorators[] = $decorator;//添加装饰器}function before(){foreach ($this->decorators as $decorator) {$decorator->before();//调用装饰器}}function after(){//这里可用栈$decorators = array_reverse($this->decorators);foreach ($decorators as $decorator) {$decorator->after();//结束装饰器}}function test() {$this->before();echo 'running<be>';$this->after();}}$decoratorTest = new DecoratorClassTest();$decoratorTest->addDecorator(new \Components\Decorator\DecoratorAttr1());$decoratorTest->addDecorator(new \Components\Decorator\DecoratorAttr2());$decoratorTest->test();

知已知彼,百战百胜。

PHP设计模式 五 (代理模式 装饰器模式)

相关文章:

你感兴趣的文章:

标签云: