wangpeng-php

导航

php的设计模式详解

适配器模式

在需要将一类对象转换成另一类对象时,请使用适配器模式。通常,开发人员通过一系列赋值代码来处理此过程,如清单 1 所示。适配器模式是整理此类代码并在其他位置重用所有赋值代码的优秀方法。此外,它还将隐藏赋值代码,如果同时还要设定格式,这样可以极大地简化工作。(原文转载http://www.ibm.com/developerworks/cn/opensource/os-php-designpatterns/)

 1 class AddressDisplay
 2 {
 3     private $addressType;
 4     private $addressText;
 5 
 6     public function setAddressType($addressType)
 7     {
 8         $this->addressType = $addressType;
 9     }
10 
11     public function getAddressType()
12     {
13         return $this->addressType;
14     }
15 
16     public function setAddressText($addressText)
17     {
18         $this->addressText = $addressText;
19     }
20 
21     public function getAddressText()
22     {
23         return $this->addressText;
24     }
25 }
26 
27 class EmailAddress
28 {
29     private $emailAddress;
30     
31     public function getEmailAddress()
32     {
33         return $this->emailAddress;
34     }
35     
36     public function setEmailAddress($address)
37     {
38         $this->emailAddress = $address;
39     }
40 }
41 
42 $emailAddress = new EmailAddress();
43 /* Populate the EmailAddress object */
44 $address = new AddressDisplay();
45 /* Here's the assignment code, where I'm assigning values 
46   from one object to another... */
47 $address->setAddressType("email");
48 $address->setAddressText($emailAddress->getEmailAddress());

此示例将使用 AddressDisplay 对象把地址显示给用户。AddressDisplay 对象有两部分:地址类型和一个格式化的地址字符串。

在实现模式(参见清单 2)后,PHP 脚本将不再需要担心如何把 EmailAddress 对象转换成 AddressDisplay 对象。那是件好事,尤其是在 AddressDisplay 对象发生更改时或者控制如何把 EmailAddress 对象转换成 AddressDisplay 对象的规则发生更改时。记住,以模块化风格设计代码的主要优点之一就是,在业务领域发生一些更改时或者需要向软件中添加新功能时尽可能少的使用更改。即使在执行普通任务(例如把一个对象的属性值赋给另一个对象)时,也请考虑使用此模式

清单 2. 使用适配器模式

 1 class EmailAddressDisplayAdapter extends AddressDisplay
 2 {
 3     public function __construct($emailAddr)
 4     {
 5         $this->setAddressType("email");
 6         $this->setAddressText($emailAddr->getEmailAddress());
 7     }
 8 }    
 9 
10 $email = new EmailAddress();
11 $email->setEmailAddress("user@example.com");
12 
13 $address = new EmailAddressDisplayAdapter($email);
14 
15 echo($address->getAddressType() . "\n") ;
16 echo($address->getAddressText());

图 1 显示了适配器模式的类图。

适配器模式的类图

替代方法

编写适配器的替代方法 —— 并且是推荐方法 —— 是实现一个接口来修改行为,而不是扩展对象。这是一种非常干净的、创建适配器的方法并且没有扩展对象的缺点。使用接口的缺点之一是需要把实现添加到适配器类中,如图 2 所示:

图 2. 适配器模式(使用接口)
适配器模式(使用接口)

迭代器模式

迭代器模式将提供一种通过对象集合或对象数组封装迭代的方法。如果需要遍历集合中不同类型的对象,则使用这种模式尤为便利。

查看上面清单 1 中的电子邮件和物理地址示例。在添加迭代器模式之前,如果要遍历个人地址,则可能要遍历物理地址并显示这些地址,然后遍历个人电子邮件地址并显示这些地址,然后遍历个人 IM 地址并显示这些地址。非常复杂的遍历!

相反,通过实现迭代器,您只需要调用 while($itr->hasNext()) 并处理下一个条目 $itr->next() 返回。清单 3 中显示了一个迭代器示例。迭代器功能强大,因为您可以添加要遍历的新类型条目,并且无需更改遍历条目的代码。例如,在 Person 示例中,可以添加 IM 地址数组;只需更新迭代器,无需更改遍历地址的任何代码。
清单 3. 使用迭代器模式遍历对象

 1 class PersonAddressIterator implements AddressIterator
 2 {
 3     private $emailAddresses;
 4     private $physicalAddresses;
 5     private $position;
 6     
 7     public function __construct($emailAddresses)
 8     {
 9         $this->emailAddresses = $emailAddresses;
10         $this->position = 0;
11     }
12     
13     public function hasNext()
14     {
15         if ($this->position >= count($this->emailAddresses) || 
16             $this->emailAddresses[$this->position] == null) {
17             return false;
18         } else {
19             return true;
20         }
21     }
22     
23     public function next()
24     {
25         $item = $this->emailAddresses[$this->position];
26         $this->position = $this->position + 1;
27         return $item;
28     }
29     
30 }

如果把 Person 对象修改为返回 AddressIterator 接口的实现,则在将实现扩展为遍历附加对象时无需修改使用迭代器的应用程序代码。您可以使用一个混合迭代器,它封装了遍历清单 3 中列出的每种地址的迭代器。本文提供了此类应用示例
图 3 显示了迭代器模式的类图。
迭代器模式的类图

装饰器 (decorator) 模式

考虑清单 4 中的代码样例。这段代码的目的是要把许多功能添加到 Build Your Own Car 站点的汽车中。每个汽车模型都有更多功能及相关价格。如果只针对两个模型,使用 if then 语句添加这些功能十分平常。但是,如果出现了新模型,则必须返回查看代码并确保语句对新模型工作正常。

 清单 4. 使用装饰器模式添加功能

 1                 
 2 require('classes.php');
 3 
 4 $auto = new Automobile();
 5 
 6 $model = new BaseAutomobileModel();
 7 
 8 $model = new SportAutomobileModel($model);
 9 
10 $model = new TouringAutomobileModel($model);
11 
12 $auto->setModel($model);
13 
14 $auto->printDescription();

进入装饰器模式,该模式允许您通过一个优秀整洁的类将此功能添加到 AutomobileModel。每个类仅仅关注其价格、选项以及添加到基本模型的方式。

图 4 显示了装饰器模式的类图。
装饰器模式的类图

装饰器模式的优点是可以轻松地同时跟踪库的多个装饰器。

如果您拥有流对象的使用经验,则一定使用过装饰器。大多数流结构(例如输出流)都是接受基本输入流的装饰器,然后通过添加附加功能来装饰它 —— 例如从文件输入流、从缓冲区输入流,等等。

委托模式

委托模式将提供一种基于各种条件委托行为的方法。考虑清单 5 中的代码。这段代码包含几个条件。根据条件,代码将选择相应类型的对象来处理请求。
清单 5. 使用条件语句来发送送货请求

 

1 pkg = new Package("Heavy Package");
2 $pkg->setWeight(100);
3 
4 if ($pkg->getWeight() > 99)
5 {
6     echo( "Shipping " . $pkg->getDescription() . " by rail.");
7 } else {
8     echo("Shipping " . $pkg->getDescription() . " by truck");
9 }

 

使用委托模式,对象将内在化(internalize)此发送过程,方法为在调用如清单 6 中的 useRail() 之类的方法时设置对相应对象的内部引用。如果处理各个包的条件发生更改或者使用新的送货类型时,则使用此模式尤为便利。


清单 6. 使用委托模式来发送送货请求

 1 require_once('classes.php');
 2 
 3 $pkg = new Package("Heavy Package");
 4 $pkg->setWeight(100);
 5 
 6 $shipper = new ShippingDelegate();
 7 
 8 if ($pkg->getWeight() > 99)
 9 {
10     $shipper->useRail();
11 }
12 
13 $shipper->deliver($pkg);

 

委托将通过调用 useRail() 或 useTruck() 方法来切换处理工作的类,从而提供动态更改行为的优点。

图 5 显示了委托模式的类图。

委托模式的类图

状态模式

状态模式类似于命令模式,但是意图截然不同。考虑下面的代码。


清单 7. 使用代码来构建机器人

 1 class Robot 
 2 {
 3 
 4     private $state;
 5 
 6     public function powerUp()
 7     {
 8         if (strcmp($state, "poweredUp") == 0)
 9         {
10             echo("Already powered up...\n");
11             /* Implementation... */
12         } else if ( strcmp($state, "powereddown") == 0) {
13             echo("Powering up now...\n");
14             /* Implementation... */
15         }
16     }
17 
18     public function powerDown()
19     {
20         if (strcmp($state, "poweredUp") == 0)
21         {
22             echo("Powering down now...\n");
23             /* Implementation... */
24         } else if ( strcmp($state, "powereddown") == 0) {
25             echo("Already powered down...\n");
26             /* Implementation... */
27         }
28     }
29 
30     /* etc... */
31 
32 }

 

在此清单中,PHP 代码表示变成一辆汽车的强大机器人的操作系统。机器人可以启动、关闭、由汽车变成机器人以及由机器人变成汽车。代码现已就绪,但是您会看到如果任何规则发生更改或者添加另一个状态则会变得十分复杂。

现在查看清单 8,其中提供了相同的逻辑处理机器人的状态,但是这一次把逻辑放入状态模式。清单 8 中的代码完成的工作与初始代码相同,但是用于处理状态的逻辑已经被放入每个状态的一个对象中。为了演示使用设计模式的优点,假定不久以后,这些机器人发现它们不应在处于机器人模式时关闭。实际上,如果它们关闭,它们必须先切换到汽车模式。如果它们已经处于汽车模式下,则机器人将关闭。使用状态模式,对代码的更改十分微小。


清单 8. 使用状态模式处理机器人的状态

 1                 
 2 $robot = new Robot();
 3 echo("\n");
 4 $robot->powerUp();
 5 echo("\n");
 6 $robot->turnIntoRobot();
 7 echo("\n");
 8 $robot->turnIntoRobot(); /* This one will just give me a message */
 9 echo("\n");
10 $robot->turnIntoVehicle();
11 echo("\n");

 

清单 9. 对一个状态对象的微小更改

 1 class NormalRobotState implements RobotState
 2 {
 3     private $robot;
 4 
 5     public function __construct($robot)
 6     {
 7         $this->robot = $robot;
 8     }
 9 
10     public function powerUp()
11     {
12         /* implementation... */
13     }
14     public function powerDown()  
15     {
16         /* First, turn into a vehicle */
17         $this->robot->setState(new VehicleRobotState($this->robot));
18         $this->robot->powerDown();
19     }
20     
21     public function turnIntoVehicle()  
22     {
23         /* implementation... */
24     }
25     
26     public function turnIntoRobot() 
27     {
28         /* implementation... */
29     }
30 }

 

图 6 中一个不太明显的地方就是状态模式中的每个对象都有对上下文对象(机器人)的引用,因此每个对象都可以把状态提升到相应的状态。


图 6. 状态模式的类图

状态模式的类图

在 PHP 代码中使用设计模式可以使代码更容易阅读、更易维护。通过使用已经建立的模式,您将从通用的设计结构中获益,从而允许团队的其他开发人员了解代码的意图。它还使您可以从其他设计者完成的工作中获益,因此无需从失败的设计理念中吸取教训。

下载

描述名字大小下载方法
样例代码 os-php-designpatterns_morepatterns.zip 4KB HTTP

posted on 2013-01-15 16:45  红尘菩提  阅读(467)  评论(0)    收藏  举报