1. policy mode concept policy mode each algorithm is encapsulated into an independent class with a common interface for a group of algorithms. This mode allows algorithm changes to be independent of customers who use algorithms. So as to make the program structure more flexible, with better scalability and maintainability 2. policy mode structure-policy mode angle
1. concept of policy mode
Policy mode encapsulates each algorithm into an independent class with a common interface for a group of algorithms. This mode allows algorithm changes to be independent from customers who use algorithms. This makes the program structure more flexible, with better scalability and maintainability.
2. Structure of policy mode
3. Role description in policy mode
Abstract Strategy role: defines the public interfaces of all supported algorithms. It is usually implemented using an interface or abstraction. Context uses this interface to call the algorithm defined by ConcreteStrategy.
ConcreteStrategy: a specific algorithm is implemented using the Strategy interface.
Environment (Context) role: Holds a reference to the Strategy class and uses a ConcreteStrategy object to configure
4. policy mode instance
For example, in the shopping cart system, when calculating the total price of a product, ordinary members must multiply the unit price of the product by the quantity. However, an 8-person discount is offered to intermediate members and a 7-fold discount is offered to senior members, in this scenario, you can use the policy mode:
* // Abstract policy role "is an interface or abstract class, inheriting a specific policy class" interface Strategy {public function computePrice ($ price );} // specific policy role-General Member policy class GenernalMember implements Strategy {public function computePrice ($ price) {return $ price ;}} // specific policy role-intermediate member policy class MiddleMember implements Strategy {public function computePrice ($ price) {return $ price * 0.8 ;}} // specific policy role-advanced member policy class HignMember implements Strategy {public function computePrice ($ price) {return $ price * 0.7 ;}} // environment role implementation class Price {// specific policy object private $ strategyInstance; // Constructor public function _ construct ($ instance) {$ this-> strategyInstance = $ instance;} public function compute ($ price) {return $ this-> strategyInstance-> computePrice ($ price );}} // the client uses $ p = new Price (new HignMember (); $ totalPrice = $ p-> compute (100); echo $ totalPrice; // 70