1. Concept
Policy mode: Encapsulates a specific set of behaviors and algorithms into classes to accommodate certain context contexts, which are policy patterns
2. function
Use policy mode to implement IOC, dependency inversion, control inversion
3. For example
If an e-commerce website system, targeting different groups of people to jump to different items, and all advertising sites show different ads
4. The problem to be resolved
1. Do not change the code because of context changes (traditionally used if else to judge)
2. If you add a new type of user, you just need to add a strategy, you do not need to if else continue adding logic in the code
3. Different places only need to implement a different strategy just fine, so you 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 '; }//If new business logic is added, there will be a lot of if else //output of the policy mode Echo $this->strategy->showad ();Echo ' <br> ';Echo $this->strategy->showcategory (); }//Policy mode to resolve, registration policy function setstrategy(userstrategy $strategy){ $this->strategy =$strategy; }}//Execute$page=NewPage;//Here according to the actual context of the environmentif(isset($_get[' Famale '])) {$strategy=NewFemaleuserstrategy ();}Else if(isset($_get[' Famale '])) {$strategy=NewMaleuserstrategy ();}//Make dependency reversal, final execution in the use of relationship bindings, output (solves the coupling problem of traditional notation)$page->setstrategy ($strategy);$page->index ();
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The strategy mode of PHP design mode