(c) design mode of PHP Project application (Strategy mode: Shopping Center cashier system)

Source: Internet
Author: User
Tags echo date

1 Policy Mode Introduction The policy pattern defines a series of algorithms, encapsulates each algorithm, and allows them to be replaced with each other. The policy pattern makes the algorithm independent of the customers who use it.

2 pattern composition 1) abstract policy role (strategy):
A policy class, usually implemented by an interface or abstract class.

2) Specific policy roles (Concretestrategy):
The related algorithms and behaviors are packaged.

3) Environmental Role (context):
Holds a reference to a policy class that is eventually called to the client.

3 mode core thought strategy mode is a method of defining some column algorithms, conceptually, all of these algorithms do the same work, but the implementation is different, it can call all the algorithms in the same way, reducing the various algorithm classes and the use of algorithm class coupling. The algorithm of the command pattern is independent of each other, and the work done by each command is different. And the strategy model is doing the same job.


4 schema Diagram
5 Program Architecture

1) abstract strategy (strategy)


Defines the interface, defines the policy algorithm to be implemented interface istrategy{    //algorithm method public    function Dofunction ();}


2) Specific strategy (CONCRETESTRATEGY)

Specific a strategy class Concretestrategya implements istrategy{public    function dofunction () {        echo ' algorithm a implementation ';    }} Specific B policy class Concretestrategyb implements istrategy{public    function dofunction () {        echo ' algorithm b implementation ';    }} Specific C policy class CONCRETESTRATEGYC implements istrategy{public    function dofunction () {        echo ' algorithm c implementation ';    }}


3) Environment Class (context)

Environment class, maintain a strategy application class context{    //policy    private $_strategy = null;    Public function __construct (IStrategy $strategy) {        $this->_strategy = $strategy;    }    Public Function DoWork () {        return $this->_strategy->dofunction ();}    }


4) clients (client)


Client Classes Class Client{public    function Main ($data) {        //a policy        $context = new Context (new Concretestrategya ()); c11/> $context->dowork ();                b strategy        $context = new Context (new Concretestrategyb ());        $context->dowork ();                C policy        $context = new Context (new CONCRETESTRATEGYC ());        $context->dowork ();    }}



6 Project Application
6.1 Requirements description To achieve a shopping mall cashier system, merchandise can have normal charges, discounted charges, rebate charges and other models ("Big talk design Mode")


6.2 Demand analysis in accordance with the requirements, you can design the charging operation as an interface algorithm, normal charges, discounted charges, rebate charges are inherited from 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/** * 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, by Cle Vercode, Create * *///defines the interface cash strategy, each strategy is implemented Acceptcash, but all are implemented to collect cash functions interface icashstrategy{//Receive cash Public function acc Eptcash ($money);} Normal charge policy class Normalstrategy implements icashstrategy{/** * return Normal amount * * @param double $money amount * @ret    Urn Double amount */Public Function Acceptcash ($money) {return $money;    }}//discount Strategy class Rebatestrategy implements icashstrategy{//discount percentage private $_moneyrebate = 1;        /** * Constructor * * @param double $rebate scale * @return void */Public function __construct ($rebate) {    $this->_moneyrebate = $rebate; }/** * Returns the normal amount * * @param double $money amount * @return Double amount */Public function Acceptcash ($mo Ney) {return $this->_moneyrebate * $money;        }}//rebate Strategy 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 amount * @return void        */Public function __construct ($moneyCondition, $moneyReturn) {$this->_moneycondition = $moneyCondition;    $this->_moneyreturn = $moneyReturn; }/** * Returns the normal amount * * @param double $money amount * @return Double amount */Public function Acceptcash ($mo            Ney) {if (!isset ($this->_moneycondition) | |!isset ($this->_moneyreturn) | | $this->_moneycondition = 0) {        return $money;    } return $money-floor ($money/$this->_moneycondition) * $this->_moneyreturn; }}

2) strategypattern.php

<?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 to change, * will not affect the use of the algorithm of 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 Cl Evercode, create * *///load all policies include_once (' strategy.php ');//Create an environment class, invoke different policies according to different requirements class cashcontext{//Policy PR    Ivate $_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 Normalstrategy ();                        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 GetResult ($money) {    return $this->_strategy->acceptcash ($money); }/** * Get results * * @param string $type type * @param int $num number * @param double $price unit Price * @retur        N 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, reducingThe coupling of low client and business logic algorithms, * makes the algorithm of business logic 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 obtains 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 d Ouble $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 ();? >



3) in strategy.php and strategypattern.php. If you need to extend multiple policies, simply inherit the premium interface to implement more classes, which are used in conjunction with the Simple factory model. Is that the program is clearer.



7 Summary 7.1 Advantages: 1, the Strategy mode provides the method to manage the related algorithm family. The hierarchy structure of a policy class defines an algorithm or a family of behaviors. Proper use of inheritance can transfer common code to the parent class, thus avoiding duplicate code.
2. The policy mode provides a way to replace the inheritance relationship. Inheritance can handle multiple algorithms or behaviors. If the policy mode is not used, then the environment class using the algorithm or behavior may have some subclasses, each of which provides a different algorithm or behavior. However, the user of the algorithm or behavior is mixed with the algorithm or the behavior itself. The logic that determines which algorithm to use or which behavior to take is mixed with the logic of the algorithm or behavior, so that it is impossible to evolve independently. Inheritance makes it impossible to dynamically change an algorithm or behavior.
3. Use the policy mode to avoid using multiple conditional transfer statements. Multiple transfer statements are difficult to maintain, and it mixes the logic of which algorithm or behavior is taken with the logic of the algorithm or the action, all in a multiple transfer statement, more primitive and backward than the method of using inheritance.


7.2 Cons: 1. The client must know all the policy classes and decide for itself which policy class to use. This means that the client must understand the differences between these algorithms in order to select the appropriate algorithm classes at the right time. In other words, the policy pattern applies only to situations where the client knows all the algorithms or behaviors.

2, the policy mode causes a lot of policy classes, each specific policy class will produce a new class. It is sometimes possible to design a policy class to be shareable by saving the environment-dependent state to the client, so that the policy class instance can be used by different clients. In other words, you can use the enjoy meta mode to reduce the number of objects.


Copyright Notice:

1) original works, from "Clevercode's blog" , please be sure to mention the following original address when reproduced , otherwise hold the copyright legal responsibility.

2) Original address : http://blog.csdn.net/clevercode/article/details/45722661 ( reprint must indicate this address ).

3) welcome everyone to pay attention to my blog more wonderful content: Http://blog.csdn.net/CleverCode.



(c) design mode of PHP Project application (Strategy mode: Shopping Center cashier system)

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.