The strategy mode of PHP design mode

Source: Internet
Author: User

Prerequisites:In software development also often encounter similar situation, to achieve a certain function has a number of algorithms or strategies, we can choose different algorithms or strategies according to the environment or conditions to complete the function. such as finding, sorting, and so on, a common method is hard-coded (Coding) in a class, if you need to provide a variety of search algorithms, you can write these algorithms into a class, in the class to provide multiple methods, each method corresponding to a specific search algorithm; These lookup algorithms are encapsulated in a unified approach, through if...else ... or case and other conditional judgment statements to make the selection. Both of these implementations can be called hard-coded, and if a new lookup algorithm needs to be added, the source code of the encapsulated algorithm class needs to be modified, and the client calling code needs to be changed. In this algorithm class to encapsulate a large number of search algorithms, the class code will be more complex, maintenance is more difficult. This is even more undesirable if we include these policies on the client, which will cause the client program to be large and difficult to maintain, and the problem will become more serious if there are a large number of algorithms to choose from.

Example 1: A menu function can determine whether to use a horizontal or vertical arrangement based on the user's "skin" preferences. Colleagues can flexibly increase the display style of the menu.

Example 2: Travel: We can have several strategies to consider: Can ride bicycles, cars, do trains, airplanes. Each policy can get the same results, but they use different resources. The choice of strategy is based on cost, time, and the ease of use of the tool in each of these ways.

IntroductionEXPLANATION One: Policy mode: Defines the algorithm family, respectivelyencapsulated so that they can be replaced with each other, this pattern allows the algorithm to change independently of the customer using the algorithm.

EXPLANATION Two: The strategy model for a set of algorithms, each algorithm is encapsulated in a separate class with a common interface, so that they can be replaced with each other. The policy pattern allows the algorithm to change without affecting the client. The strategy model separates behavior from the environment. The Environment class is responsible for maintaining and querying behavior classes, and various algorithms are available in specific policy classes. Because the algorithm and the environment independent, the algorithm increases or decreases, the modification will not affect the environment and the client.

Encapsulation: The behavior is encapsulated by an interface, and we can take the frequently changed parts out of the current class separately and use the interface to encapsulate them individually. Replace each other: we encapsulate the interface, and change the algorithm by specifying different interfaces to implement the class. Mind Mapping

Let me explain the process of this mind mapping: 1. Joe did a fairly successful simulation of the duck game. A super Class Duck is designed, and then the various ducks inherit this class. 2. Later the client proposed to let the duck have the ability to fly.   So Joe adds a fly () method to the superclass so that the following subclasses have a flying behavior. The problem is:1> original duck of the sub-class unexpectedly has rubber duck, rubber duck is not fly.                 --joe The Fly () method of the rubber duck is set to empty using the overloaded way. 2> cover Fly (), we see the Rubber Duck fly (), there is no code, if we add another non-flying ducks in the future, then I would like to deal with it?—— sothe code repeats!3. The above 2 way we know there is a problem, so Joe thought to make duck interface, so that each subclass must implement the method in duck.     This ensures that each duck can add behavior according to its own needs. The problem: the product is often in the update, the specifications are constantly changing. The result is that whenever a new duck is available, Joe is forced to check to see if the subclass covers the Fly () method. --When you modify a behavior, you have to follow it down and modify it in each class that defines the behavior. 4. In combination with the above questions, Joe thought of pulling out the parts of the change that never changed. For example, we do a separate interface Flybehavior for the fly () behavior. If Ducks want to fly the function, we let the duck achieve flybehavior. 5. Further study: We want the Ducks to have different flight functions so that they do different flight movements during operation. Let the duck class implement the interface, only let the duck have a behavior. So Joe, thinking of using the combination of prevention, when the Ducks need other flight function requirements, we can use the Setbehavior () way, the specific way of flight.
<?phpinterface flybehavior{public    function Fly (),} class Flywithwings implements flybehavior{    public Function Fly () {        echo "Fly with Wings \ n";    }} class Flywithno implements flybehavior{public    function Fly () {
   echo "Fly with No Wings \ n";    }}

Class duck{    private $_flybehavior;    Public Function Performfly () {        $this->_flybehavior->fly ();    }     Public Function Setflybehavior (Flybehavior $behavior) {        $this->_flybehavior = $behavior;    }} class Rubberduck extends duck{}//Test case$duck = new Rubberduck (); /*  want the duck to fly with wings */$duck->setflybehavior (new flywithwings); $duck->performfly ();             /*  want the duck to fly without wings * * $duck->setflybehavior (new Flywithno ()); $duck->performfly ();
Summary:In general, our design principles in development are as follows: 1. Find out where changes may be needed in the application, separate them, and don't mix with the code that doesn't need to change; 2. Programming for the interface, not for the implementation of programming; 3. Multi-use combination, less inheritance;
1) The strategy mode is a relatively easy to understand and use the design pattern, the strategy pattern is the encapsulation of the algorithm, it divides the responsibility of the algorithm and the algorithm itself, delegated to different object management. The strategy pattern typically encapsulates a series of algorithms into a set of policy classes as subclasses of an abstract policy class. In a word, it is "preparing a set of algorithms and encapsulating each algorithm so that they can be interchanged". 2) in policy mode, it is up to the client to decide under what circumstances the specific policy role should be used. 2) 3) The strategy mode only encapsulates the algorithm, provides a new algorithm to insert into the existing system, and the old algorithm from the system "retirement" convenience, the strategy mode does not decide when to use which algorithm, the choice of the algorithm is determined by the client.  This improves the flexibility of the system to a certain extent, but the client needs to understand the differences between all the specific policy classes in order to choose the appropriate algorithm, which is one of the drawbacks of the strategy model, which in some way increases the difficulty of using the client.
Four. With other related modes

1) State mode

The strategy pattern is quite similar to many other design patterns. The biggest difference between the policy mode and the state mode is that the policy mode is only the condition selection is executed once, while the state pattern changes the execution mode continuously as the instance parameter (the state of the object instance) changes. In other words, the policy pattern changes the execution mode only when the object is initialized, while the state pattern dynamically alters the execution pattern of the object instance based on the cycle time of the object instance.

• The number of environment class States can be used to determine whether to use the policy mode or the state mode. • The environment class of the strategy mode chooses a specific policy class, the specific policy class does not need to care about the environment class, but the environment class of the state pattern needs to put into a concrete state in order to realize the State switching through its method, so there is a bidirectional association between the Environment class and the State class. • When using the policy mode, the client needs to know which specific policy is selected, while using state mode, the client does not need to be concerned about the state, and the state of the environment class is automatically converted according to the user's operation. • If the objects of a class in a system have multiple states, behave differently in different states, and use state mode when transformations can occur between these states, if there are multiple implementations of a class in a system, and these implementations are interchangeable, use the policy mode.

2) The difference between a simple factory:

The factory pattern is a create pattern that focuses on object creation and provides an interface for creating objects. The creation of objects has nothing to do with the specific use of the client.
The policy pattern is an object-behavioral pattern that focuses on the encapsulation of behaviors and algorithms. It defines a series of algorithms that encapsulate each algorithm and make them interchangeable with each other. Allows the algorithm to change independently of the customer using it

Use the examples of travel we mentioned above:
We're going on a trip. Strategy mode approach: There are several options for you to choose to travel, whether to choose a train or to ride a bike, and it is entirely up to the customer to build a travel plan (e.g. you need to buy a train ticket, or a ticket). And the factory model is when you decide what kind of travel plan you want, don't pay attention to how the travel plan is created for you, that is, you tell me the name of the project, and then the factory instead of you to build the specific plan (the factory instead of you to buy train tickets).

In the example above, the client code:
$person = new Personcontext (new Trainstrategy ());
$person->travel ();
We see that customers need to create specific travel (new Trainstrategy ()) instances themselves. The specific instance is passed.
And the factory model you just have to tell what kind of travel you can, not pass a specific instance, but an identity (Travel plan identification).

Reference: http://www.iam3y.com/html/750.htmlhttp://www.howzhi.com/group/php/discuss/3456 design mode course: http://www.howzhi.com/ Course/1108/?ref=search_recommend
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.