Simple Example of PHP implementation policy mode, php Policy Example
This article describes the policy Mode Implemented by PHP. We will share this with you for your reference. The details are as follows:
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:
<? Php/*** policy mode instance ** // abstract policy role "for interface or abstract class, inherit 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 fun Ction computePrice ($ price) {return $ price * 0.7; }}// class Price of the Environment Role Implementation class {// specific policy object private $ strategyInstance; // 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?>