Simple Example of PHP implementation policy mode, php Policy Example

Source: Internet
Author: User

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?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.