PHP设计模式之装饰器模式定义与用法详解(2)

<?php class Video extends Decorator { public function __construct(IComponent $siteNow) { $this->site = $siteNow; } public function getSite() { $format = "<br /> Video"; return $this->site->getSite() . $format; } public function getPrice() { return 350 + $this->site->getPrice(); } }

DataBase.php

<?php class DataBase extends Decorator { public function __construct(IComponent $siteNow) { $this->site = $siteNow; } public function getSite() { $format = "<br /> DataBase"; return $this->site->getSite() . $format; } public function getPrice() { return 800 + $this->site->getPrice(); } }

测试这个应用时,可以看到,在基本的价格之上还会增加各个装饰器的价格.另外还能指定装饰器名的格式, 增加了两个空格,使之缩进

装饰器实现中最重要的元素之五就是构造函数, 要为构造函数提供一个组件类型. 由于这里只有一个具体组件, 所有装饰器的实例化都会使用这个组件. 使用多个组件时, 装饰器可以包装应用中的一部分或全部组件, 也可以不包装任何组件.

客户

Client类并不是这个设计模式的一部分, 但是正确使用Client类至关重要.每个装饰器在实例化时"包装"组件, 不过, 首先必须创建一个要包装的对象, 这里是BasicSite类实例

Client.php

<?php function __autoload($class_name) { include $class_name . '.php'; } class Client { private $basicSite; public function __construct() { $this->basicSite = new BasicSite(); $this->basicSite = $this->WrapComponent($this->basicSite); $siteShow = $this->basicSite->getSite(); $format = "<br /> <strong>Total= $"; $price = $this->basicSite->getPrice(); echo $siteShow . $format . $price . "</strong>"; } private function WrapComponent(IComponent $component) { $component = new Maintenance($component); $component = new Video($component); $component = new DataBase($component); return $component; } } $worker = new Client();

wrapComponent()方法检查传入的BasicSite实例, 以确保参数有正确的数据类型(IComponent), 然后分别实例化3个装饰器, 对该实例对象进行装饰.

Basic Site
  Maintenance
  Video
  DataBase
  Total= $3300

适配器和装饰器模式都有另外一个名字"包装器"(wrapper)".

适配器可以"包装"一个对象, 创建一个与Adaptee兼容的接口, 而无须对它做任何修改.

装饰器也可以"包装"一个组件对象, 这样就能为这个已胡的组件增加职责, 而无须对它做任何修改.

下面的代码展示了Client如何将组件对象($component)包装在装饰器(Maintence)中:

$component = new Maintenance($component);

类似于"接口", 在计算机编程中用到"包装器"时, 不同的上下文会有不同的用法和含义. 一般来讲, 在设计模式中使用"包装器"是为了处理接口的不兼容, 或者希望为组件增加功能,包装器就表示用来减少不兼容性的策略.

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP基本语法入门教程》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/a0344bc032a51082afe4f307024c4ae8.html