Policy pattern: Defines a series of algorithms that encapsulate each algorithm and allow them to be replaced by each other. This mode allows the algorithm to vary independently from the customer who uses it. The policy pattern distinguishes the object itself from the operation rules, and its function is very powerful, because the core idea of the design pattern itself is the idea of the polymorphism of object-oriented programming.
That is, we plan to travel, we can have a few strategies to consider, can ride bicycles, cars, do trains, airplanes.
"Primary role in policy mode"
Environment Class (context): Configured with a Concretestrategy object. Maintains a reference to the Strategy object. You can define an interface to let strategy access its data. (Interface class or abstract class) must consider means of transport, transport to consider the time (interface class or abstract class to implement methods), fees and other issues
Abstract policy Class (strategy): A public interface that defines all supported algorithms. The context uses this interface to invoke an algorithm defined by a concretestrategy. (The realization of environmental class, choose the range of vehicles, trains, airplanes, bicycles ...) )
Specific policy class (Concretestrategy): Implement a specific algorithm by strategy interface. (Give us a choice of the mode of transport information)
"Policy Mode PHP Example"
# Environment Class (context) interface traveltool{public function usetime ();
Public function money ();
# Abstract policy classes (strategy) class Plane implements Traveltool {# aircraft public Function Usetime () {return ' 1 h ';
Public Function Money () {return ' $ ';
} class Train implements Traveltool {# train public Function Usetime () {return ' 3 h ';
Public Function Money () {return ' $ ';
} # Specific policy class (Concretestrategy) classes dotravel{public $obj; Public function __construct ($method) {$temp = new Reflectionclass ($method);
# See other blogs with a reflection on the learning http://www.php.net/manual/zh/book.reflection.php $this->obj = $temp->newinstance ();
Public Function Money () {echo $this->obj->money ();
The Public Function Usetime () {echo $this->obj->usetime ();
} $obj = new Dotravel (' Train ');
$obj->money ();
echo "<br/>";
$obj->usetime ();
For more detailed content (advantages, disadvantages, applicability) see here reproduced in http://www.howzhi.com/group/php/discuss/3456