PHP policy mode

Source: Internet
Author: User
Tags echo date
This article to share the content is about the PHP strategy model, has a certain reference value, the need for friends can refer to

For example: an e-commerce website system for male female users to jump to different product categories, and all advertising sites show different ads

6 Project Application


6.1 Requirements Description

To achieve a shopping center cash register system, merchandise can have normal charges, discount charges, rebate charges and other models ("Big talk design Mode")


6.2 Demand Analysis

In accordance with the requirements, you can design the charge operation as an interface algorithm, normal charges, discounted charges, rebate charges are inherited this interface, the implementation of different strategy algorithms. Then design an environment class to maintain an instance of the policy.


6.3 Design Architecture Diagram



6.4 Program source code download

http://download.csdn.net/detail/clevercode/8700009

6.5 Program Description


1) strategy.php




[PHP] view plain copy


  1. <?php/** * strategy.php * Policy class: Defines a series of algorithms that are the same work done, but with different implementations.  * Special statement: The source code is based on the "Big Talk Design Model" in the Book of C # to change into PHP code, and the book * Code will be changed and optimized. * * Copyright (c) http://blog.csdn.net/CleverCode * * Modification History: *--------------------* 2015/5/5, B Y Clevercode, Create *///define Interface cash strategy, each strategy is specifically implemented Acceptcash, but all are implemented to collect cash functions interface icashstrategy{//collect cash PU  Blic function Acceptcash ($money);  }//Normal charge policy class Normalstrategy implements icashstrategy{/** * return Normal amount * * @param double $money      Amount * @return Double amount */Public Function Acceptcash ($money) {return $money;        }}//Discount policy class Rebatestrategy implements icashstrategy{//discount percentage private $_moneyrebate = 1; /** * Constructor * * @param double $rebate scale * @return void */Public function __construct ($rebat      e) {$this->_moneyrebate = $rebate; }/** * Returns the normal amount * * @param double $money amount     * @return Double Amount */Public Function Acceptcash ($money) {return $this->_moneyrebate * $money;            }}//Rebate policy class Returnstrategy implements icashstrategy{//Rebate condition private $_moneycondition = null;        Rebate how much private $_moneyreturn = null; /** * Constructor * * @param double $moneyCondition rebate Condition * @return Double $moneyReturn rebate how much * @return Vo ID */Public function __construct ($moneyCondition, $moneyReturn) {$this->_moneycondition = $moneyCon          dition;      $this->_moneyreturn = $moneyReturn; }/** * Returns the normal amount * * @param double $money amount * @return Double amount */Public Function acc Eptcash ($money) {if (!isset ($this->_moneycondition) | |!isset ($this->_moneyreturn) | | $this->_moneycondi          tion = = 0) {return $money; } return $money-floor ($money/$this->_moneycondition) * $this->_moneyReturn; }  }


2) strategypattern.php





[PHP] view plain copy


  1. <?php/** * strategypattern.php * design mode: Policy Mode * * Mode Introduction: * It defines the algorithm family, respectively encapsulated, so that they can replace each other, this mode allows the algorithm changes, * does not affect the use of  Algorithm for the customer.  * Policy mode is a method of defining some of the column algorithms, conceptually, all of these algorithms are doing the same work, just implement different, it can call all the algorithms in the same way, reduce the various algorithm classes * and use the algorithm class coupling. * The source code of various checkout methods, in fact, are in the checkout, but the specific implementation is indeed different. The strategy mode differs from the * command pattern in that the algorithm of the command pattern is independent of each other, and the work done by each command is different.            and the Strategy mode * is doing a job.  * Special statement: The source code is based on the "Big Talk Design Model" in the Book of C # to change into PHP code, and the book * Code will be changed and optimized. * * Copyright (c) http://blog.csdn.net/CleverCode * * Modification History: *--------------------* 2015/5/14,    by Clevercode, Create *///Load All Strategy include_once (' strategy.php ');        Create an environment class that invokes different policies according to different requirements class cashcontext{//policy private $_strategy = null; /** * Constructor * * @param string $type type * @return void */Public function __construct ($type =          NULL) {if (!isset ($type)) {return;      } $this->setcashstrategy ($type);      }/** * Set policy (simple factory mixed with policy mode) ** @param string $type type * @return void */Public Function setcashstrategy ($type) {$cs = null; Switch ($type) {//normal policy case ' normal ': $cs = new NormalS                  Trategy ();                            Break                  Discount strategy case ' Rebate8 ': $cs = new Rebatestrategy (0.8);                            Break                  Rebate strategy case ' return300to100 ': $cs = new Returnstrategy (300, 100);          Break      } $this->_strategy = $cs; }/** * Get results * * @param double $money amount * @return double */Public function Getresul      T ($money) {return $this->_strategy->acceptcash ($money);      }/** * Get results * * @param string $type type * @param int $num number * @param double $price Unit Price * @return Double */Public function Getresultall ($tyPE, $num, $price) {$this->setcashstrategy ($type);      return $this->getresult ($num * $price); }}/* Client class * Allows the client and business logic to be separated as much as possible, reducing the coupling between client and business logic algorithms, * making business logic algorithms more portable */class client{Public Function main ()                    {$total = 0;                    $cashContext = new Cashcontext ();          Purchase quantity $numA = 10;          Unit Price $priceA = 100;          The policy mode obtains the result $totalA = $cashContext->getresultall (' normal ', $numA, $priceA);                    $this->display (' A ', ' normal ', $numA, $priceA, $totalA);          Purchase quantity $numB = 5;          Unit Price $priceB = 100;          The discount strategy obtains the result $totalB = $cashContext->getresultall (' Rebate8 ', $numB, $priceB);                    $this->display (' B ', ' Rebate8 ', $numB, $priceB, $totalB);          Purchase quantity $numC = 10;          Unit Price $priceC = 100; The rebate strategy Gets the result $totalC = $cashContext->getresultall (' return300to100 ', $nuMC, $priceC);      $this->display (' C ', ' return300to100 ', $numC, $priceC, $totalC);      /** * Print * * @param string $name Product Name * @param string $type type * @param int $num number          * @param double $price Unit Price * @return Double */Public function display ($name, $type, $num, $price, $total) { echo Date (' y-m-d h:i:s ').      ", $name, [$type],num: $num, Price: $price, total: $total \ r \ n";      }}/** * Program entry */function Start () {$client = new client ();  $client->main ();    } start (); ?>

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.