return true; } }
class MailCommand implements ICommand { public function onCommand( $name, $args ) { if ( $name != 'mail' ) return false; echo( "MailCommand handling 'mail'\n" ); return true; } }
$cc = new CommandChain(); $cc->addCommand( new UserCommand() ); $cc->addCommand( new MailCommand() ); $cc->runCommand( 'addUser', null ); $cc->runCommand( 'mail', null ); ?> 此代码定义维护 ICommand 对象列表的 CommandChain 类。两个类都可以实现 ICommand 接口 —— 一个对邮件的请求作出响应,另一个对添加用户作出响应。 图 5 给出了 UML。
 图 5. 命令链及其相关命令 如果您运行包含某些测试代码的脚本,则会得到以下输出:
% php chain.php UserCommand handling 'addUser' MailCommand handling 'mail' % 代码首先创建 CommandChain 对象,并为它添加两个命令对象的实例。然后运行两个命令以查看谁对这些命令作出了响应。如果命令的名称匹配 UserCommand 或 MailCommand,则代码失败,不发生任何操作。 为处理请求而创建可扩展的架构时,命令链模式很有价值,使用它可以解决许多问题。
策略模式
我们讲述的最后一个设计模式是策略 模式。在此模式中,算法是从复杂类提取的,因而可以方便地替换。例如,如果要更改搜索引擎中排列页的方法,则策略模式是一个不错的选择。思考一下搜索引擎的几个部分 —— 一部分遍历页面,一部分对每页排列,另一部分基于排列的结果排序。在复杂的示例中,这些部分都在同一个类中。通过使用策略模式,您可将排列部分放入另一个类中,以便更改页排列的方式,而不影响搜索引擎的其余代码。
作为一个较简单的示例,清单 6 显示了一个用户列表类,它提供了一个根据一组即插即用的策略查找一组用户的方法。
清单 6. Strategy.php
<?php interface IStrategy { function filter( $record ); }
class FindAfterStrategy implements IStrategy { private $_name;
public function __construct( $name ) { $this->_name = $name; }
public function filter( $record ) { return strcmp( $this->_name, $record ) <= 0; } }
class RandomStrategy implements IStrategy { public function filter( $record ) { return rand( 0, 1 ) >= 0.5; } }
上一页 [1] [2] [3] [4] [5] [6] 下一页 |