PHP design mode: Policy mode; php design mode Policy
Strategy pattern is a type in behavior pattern. The behavior pattern describes how an application operates.
Policy mode: defines algorithm families, which are encapsulated separately so that they can be replaced with each other. This mode allows algorithm changes to be independent of algorithm customers.
- Encapsulation: encapsulate behavior with Interfaces. We can extract frequently changed parts from the current class and encapsulate them separately using interfaces.
- Replace each other: We have encapsulated interfaces and implemented classes to change algorithms by specifying different interfaces.
<? Php/*** define interface */interface car {public function run ();} /*** interface algorithm implementation * @ return [type] [description] */class bmwCar implements car {public function run () {echo "BMW on the road Mercedes \ n ";}} /*** interface algorithm implementation * @ return [type] [description] */class audiCar implements car {public function run () {echo "Audi car on the road Benz \ n" ;}/ *** class using different algorithms * @ param integer $ speed [description] */class chooseCar {public $ speed; function _ construct ($ speed = 60) {$ this-> speed = $ speed;} function start ($ brand) {$ car = null; switch ($ brand) {case "bmw": $ car = new bmwCar (); break; case "audi": $ car = new audiCar (); break; default: $ car = new bmwCar () ;}$ car-> run (); echo "speed: {$ this-> speed} km/h ";}} $ car = new chooseCar (180); $ car-> start ("audi ");
// Output
The speed of the Audi car on the road is 180 km/h
The rule mode immediately changes an algorithm. When the class we use is simple but not correlated with each other, the rule mode is very useful in scenarios with specific behavior differences.
In addition to the programming field, there are many examples of policy patterns. For example:
If I need to go to work from home in the morning, I have several strategies to consider: I can take the subway, take a bus, walk or another way. Each policy can get the same result, but different resources are used.