1. Concept
Policy mode: Encapsulates a specific set of behaviors and algorithms into classes. In order to adapt to certain contexts, this pattern is the policy mode
2. function
Use policy mode to implement IOC, dependency inversion, control inversion
3. For example
If an e-commerce site system, for different groups of people to jump to different categories of goods. And all the ads are showing different ads.
4. The problem to be resolved
1. No code changes due to context changes (traditionally used if
else
to infer)
2. Suppose that a new type of user is added, just need to add a strategy, do not need if
else
to continue to add logic in the code
3. Different places just need to run a different strategy just fine, so that can solve the problem
4. 从硬编码到解耦的使用
5.最基本的是攻克了程序中的分支逻辑
5. Actual combat Code Show 5.1 interface file for policy declaration
interface UserStrategy { function showAd(); function showCategory();
5.2 Defining strategies for female users
class FemaleUserStrategy implements UserStrategy { function showAd() { echo"2014新款女装"; } function showCategory() { echo"服装";
5.3 Defining strategies for male users
class MaleUserStrategy implements UserStrategy { function showAd() { echo"IPhone6"; } function showCategory() { echo"电子产品";
6. Page display and use
class Page{ //Save policy Object protected $strategy;//Home Information output function index(){ //traditional notation, with output if(isset($_get[' Famale '])) {Echo ' Women '; }Else if(isset($_get[' Famale '])) {Echo ' Male '; }//Assuming there is a lot of new business logic behind the If Else //output of the policy mode Echo $this->strategy->showad ();Echo ' <br> ';Echo $this->strategy->showcategory (); }//strategy mode to solve, register strategy function setstrategy(userstrategy $strategy){ $this->strategy =$strategy; }}//Run$page=NewPage;//Here according to the environment of the actual contextif(isset($_get[' Famale '])) {$strategy=NewFemaleuserstrategy ();}Else if(isset($_get[' Male '])) {$strategy=NewMaleuserstrategy ();}//Make dependency reversal, finally run in the use of relationship bindings, output (overcoming the coupling problem of traditional notation)$page->setstrategy ($strategy);$page->index ();
The strategy mode of PHP design mode