The strategy mode of PHP design mode

Source: Internet
Author: User
Tags define abstract

Brief introduction

The policy pattern defines the algorithm families, which are encapsulated separately so that they can be replaced by each other. This pattern allows the algorithm to be independent of the client using it and change independently.

Composition

Abstract policy role: A policy class, usually implemented by an interface or abstract class.

Specific policy role: wrapping the relevant algorithms and behaviors.

Environment role: holds a reference to a policy class that is eventually called to the client.

Application Scenarios

Multiple classes differ only in the performance behavior, and you can use the policy mode to dynamically select the behavior that you want to perform at run time.

Different strategies (algorithms) need to be used in different situations, or policies may be implemented in other ways in the future.

The details of the implementation of the specific strategy (algorithm) are hidden from the customer.

Realize

Steps

Define abstract role classes (common abstractions that define each implementation)

Define a specific policy class (a common way to implement the parent class specifically)

Define Environment Role classes (Receive save instance, unified execution policy class interface method)

Code

<?phpheader (' Content-type:text/html;charset=utf-8 ');/** * Strategy Mode Demo Code * * In order to better highlight the "strategy", we take a trip as an example of the demonstration, Daily trips can be divided into the following tools: self-driving, bus, Subway, train, plane, ship * * See code below, understand what strategy mode *//** * Interface travel abstract Policy Role * Contract specific method */interface travel{PU Blic function Go ();} /** * Class selfdriving specific policy role * self-driving */class byselfdriving implements travel{public function go () {echo ' I    Driving out of the car to play <br> '; }}/** * Class Bybus specific policy role * Bus */class Bybus implements travel {public function go () {echo ' I go out to play by bus <br&    gt; '; }}/** * Class Bymetro specific policy role * by Metro */class Bymetro implements travel{public function go () {echo ' I go out to play by subway &lt    ;br> '; }}/** * Class Bytrain specific policy role * by train */class Bytrain implements travel{public function go () {echo ' I go out to play by train &lt    ;br> '; }}/** * Class Byairplane specific policy role * by plane */class Byairplane implements travel{public function go () {echo ' I fly    Go out to play <br> '; }}/** * Class bysteamship specific policy role * by steamer */class Bysteamship implements Travel{public Function Go () {echo ' I go out to play <br> by ship ';    }}/** * Class Mine Environment role */class mine{private $_strategy;    Private $_ischange = false; /** * Construction Method * The concept of dependency injection and type constraint is used here, please refer to * 1 for details. A chat about PHP's Dependency injection (DI) and control inversion (IoC) * @link HTTPS://SEGMENTFAULT.COM/A/1 190000007209266 * 2. On the type constraint of PHP * @link https://segmentfault.com/a/1190000007226476 * * @param travel $trav    El * * Public function __construct (travel $travel) {$this->_strategy = $travel; } * * * * * * * * * * * * * * @param travel $travel */Public Function change (tour $travel) {$this/**        ->_strategy = $travel;    $this->_ischange = true;            } public Function Gotravel () {if ($this->_ischange) {echo ' Now changes the mind, ';        $this->_strategy->go ();        } else {$this->_strategy->go (); }}}/** * Client uses */$strategy = new Mine (new Bybus ());//bus $strategy->gotravel ();//By Subway $strateGy->change (New Bymetro ()); $strategy->gotravel ();//self-driving $strategy->change (New byselfdriving ()); $strategy- >gotravel ();//Other depending on the application choice to achieve

Run results

I go out to play by bus
Change my mind now, I go out to play by subway
Change my mind now, I'll drive out and play.

Advantages and Disadvantages

Advantages

The policy pattern provides a way to manage the associated algorithm families. 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.

The policy pattern 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.

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.

Disadvantages

The client must know all the policy classes and decide for themselves 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.

The policy pattern causes a lot of policy classes, and each specific policy class produces 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.

  • Related Article

    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.