Design Mode (18) Strategy Mode strategy (object behavior type)

Source: Internet
Author: User

Design Mode (18) Strategy Mode strategy (object behavior type)

1. Overview

Similar situations are often encountered in software development. There are multiple algorithms or policies for implementing a function. We can select different algorithms or policies based on different environments or conditions to complete the function. Such as search and sorting, a frequently used method is hard coding in a class. If you need to provide multiple search algorithms, you can write these algorithms into a class, multiple methods are provided in this class, and each method corresponds to a specific search algorithm. Of course, these search algorithms can also be encapsulated in a unified method, through if... Else... Or case and other conditional inference statements for selection. Both of these methods can be called hard encoding. If you need to add a new search algorithm, you need to modify the source code of the encapsulated algorithm class. Replace the search algorithm, you also need to modify the client call code. A large number of search algorithms are encapsulated in this algorithm class. This type of code is complicated and difficult to maintain. If we include these policies in the client, this approach is not desirable and will lead to a large client program and difficult to maintain. If there are a large number of available algorithms, the problem will become more serious.

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

Example 2: traveling: We have several strategies to consider: riding bicycles, cars, trains, and airplanes. Each policy can get the same result, but they use different resources. The policy is selected based on the cost, time, and ease of use of the tool.



2. Problem

How can we split algorithms and objects so that algorithms can change independently of customers who use them?

3. Solution

Rule mode: SetTo encapsulate and replace each algorithm. This mode allows algorithms to change independently of customers who use it. It is also called a policy ). (Definea family of algorithms, encapsulate each one, andmake them interchangeable. Strategy lets the algorithmvary independently from clients that use it .)

The rule mode separates objects from operation rules and has powerful functions. Because the core idea of this design mode is the concept of object-oriented programming.

4. Applicability

Use the strategy mode when the following conditions exist:
1 )? Many related classes have different behaviors. "Policy" provides a method to configure a class with one of multiple actions. That is, a system must dynamically select one of several algorithms.
2 )? Different variants of an algorithm are required. For example, you may define algorithms that reflect different space/time trade-offs. When these variants are implemented as class layers of an algorithm, the policy mode can be used.
3 )? Algorithms use data that customers should not know. Policy modes can be used to avoid exposing complex algorithm-related data structures.
4 )? A class defines multiple behaviors, and these behaviors appear in the form of multiple conditional statements in the operations of this class. Move related condition branches into their respective strategy classes to replace these condition statements.

5. Structure


6. Composition of the Mode

Context: A concretestrategy object is used for configuration. Maintain a reference to the strategy object. You can define an interface for strategy to ask its data.
Abstract strategy: defines the public interfaces of all supported algorithms. Context uses this interface to call a concretestrategy-defined algorithm.
Concretestrategy: A detailed algorithm is implemented using the strategy interface.

7. Effect

The Strategy Mode has the following advantages:
1) related algorithm series strategy class layers define a series of reusable algorithms or actions for context. Inheritance helps to analyze the common functions of these algorithms.
2) provide a way to replace the inheritance relationship: inheritance provides a way to support multiple algorithms or actions. You can directly generate a subclass of the context class to give it different behaviors. However, this will combine the implementation of the algorithm with the implementation of the context to make the context difficult to understand, maintain, and expand, the algorithm cannot be changed dynamically. Finally, you get a bunch of related classes. The only difference between them is the algorithm or behavior they use. Encapsulating an algorithm in an independent strategy class enables you to change it independently of its context, making it easy to switch, understand, and expand.
3) Some if else condition statements are eliminated: The Strategy mode provides an option other than the action needed to select with the condition statement. When different behaviors are stacked in a class, it is very difficult to avoid using conditional statements to select appropriate behaviors. Encapsulate behaviors in independent strategy classes to remove these conditional statements. Code that contains many conditional statements usually means that the Strategy Mode is required.
4) The Strategy Mode can provide different implementations of the same behavior. Customers can choose from different policies based on the trade-off between time and space.

Disadvantages of Strategy Mode:

1) The client must know all the policy classes and decide which policy class to use: This mode has a potential disadvantage, that is, to select a proper strategy, a customer must know what the difference between these strategies is. At this time, you may have to expose detailed implementation issues to the customer. Therefore, the strategy mode is required only when these different behavior variants are related to the customer.
2) communication overhead between strategy and Context: no matter whether the algorithms implemented by concretestrategy are simple or complex, they all share the interfaces defined by strategy. Therefore, it is very likely that some concretestrategy will not use all the information transmitted to them through this interface; simple concretestrategy may not use whatever information in it! This means that sometimes context will create and initialize the number of partitions that will never be used. If this problem exists, a closer coupling between strategy and context is required.
3) The policy mode will generate many policy classes: the number of objects can be reduced to a certain extent by using the enjoy mode. The number of objects added. Strategy adds the number of objects in an application. Sometimes you can implement strategy as a stateless object shared by various context to reduce this marketing. All other statuses are maintained by context. Context passes this state in every request to the strategy object. Shared strategy should not maintain the status between calls.

8. Implementation

1) Travel and Tourism:

UML:


Code implementation:

<? PHP/*** policy pattern * defines a series of algorithms that encapsulate each algorithm and make them replaceable. This mode allows the algorithm to change independently of its customers ** // ** Travel **/interface travelstrategy {public function travelalgorithm ();} /*** concretestrategy 1: Fly */class airplanelstrategy implements travelstrategy {public function travelalgorithm () {echo "travel by airplain ", "<br> \ r \ n" ;}}/*** detailed strategy class (concretestrategy) 2: By train */class trainstrategy implements travelstrategy {public function travelalgorithm () {echo "travel by tr Ain "," <br> \ r \ n ";}}/*** concretestrategy 3: bike ride */class bicyclestrategy implements travelstrategy {public function travelalgorithm () {echo "travel by bicycle", "<br> \ r \ n" ;}}/ *** context: Use a concretestrategy object for configuration. Maintain a reference to the strategy object. You can define an interface for strategy to ask its data. * Algorithm solution class: */class personcontext {private $ _ strategy = NULL; public function _ construct (travelstrategy $ travel) {$ this-> _ strategy = $ travel;}/*** travel */Public Function settravelstrategy (travelstrategy $ travel) {$ this-> _ strategy = $ travel ;} /*** travel */Public Function travel () {return $ this-> _ strategy-> travelalgorithm ();}} // traveling by train $ person = new personcontext (New trainstrategy (); $ person-> Trav El (); // change the bike ride $ person-> settravelstrategy (New bicyclestrategy (); $ person-> travel ();?>

 

2) sorting Policy: A system provides a class for operating array data, which encapsulates common operations on arrays,

Such as searching for array elements and sorting array elements. Taking sorting as an example, this array operation class is designed using policy mode,

This allows the client to dynamically change the Sorting Algorithm and can select Bubble sorting or sort or insert sorting as needed,

You can also flexibly add new sorting algorithms.

9. Other related models

1) status Mode

The rule mode is similar to many other design modes. The biggest difference between the rule mode and the state mode is that the rule mode only runs once when the condition is selected, and the state mode is based on the number of instance shards (the status of the object instance) the operation mode is constantly changed. In other words, the policy mode is only in

During object initialization, the running mode is changed dynamically based on the cycle time of the object instance.

? The number of environment statuses can be used to determine whether to use the policy mode or the State mode .? The environment class of the Policy mode selects a detailed strategy class, and the detailed strategy class does not need to care about the environment class. The environment class of the state mode needs to be put into a detailed state due to external factors, so that the Status switching can be realized through its method, therefore, there is a two-way association between the Environment class and the status class .? When using the Policy mode, the client needs to know which detailed policy is selected. When using the status mode, the client does not need to care about the detailed status, the environment status is automatically converted based on user operations .? Assume that there are multiple States for an object of a class in the system, and the behavior varies in different States, and the status mode can be used when the States change; assume that a row of a class in the system has multiple implementation methods, and these implementation methods can be switched using the Policy mode.

2) differences between simple factories: Click to open the link

The factory mode is the creation mode. It focuses on Object creation and provides interfaces for object creation, so that object creation is irrelevant to detailed customers.
Policy mode is the object behavior mode, which focuses on Behavior and algorithm encapsulation. It defines a series of algorithms, encapsulates each algorithm, and makes them replaceable. This allows algorithms to change independently of customers who use it.

Example of traveling as mentioned above:
Let's go on a trip. Strategy Mode: There are several solutions for you to choose to travel. If you choose a train, you can still ride a bicycle. Some customers decide to build a travel solution (for example, you need to buy a train ticket on your own, or air tickets ). The factory model is the travel solution you decide, so you don't need to pay attention to how the travel solution is created for you. That is to say, you can tell me the name of the solution, then, the factory will replace you to build detailed solutions (the factory will replace you with buying train tickets ).

In the above example, the client code is as follows:
$ Person = new personcontext (New trainstrategy ());
$ Person-> travel ();
We can see that customers need to create their own travel details (New trainstrategy () instances. The detailed instance is passed.
In the factory model, you only need to tell which kind of trip can be done, instead of passing a detailed instance, but an identifier (travel plan identifier ).

10. Summary and Analysis

1) The policy mode is a design mode that is easier to understand and use. The policy mode is an encapsulation of the algorithm. It splits the responsibility of the algorithm and the algorithm itself, delegate to different object management. Rule mode encapsulates a series of algorithms into a series of policy classes and serves as a subclass of an abstract policy class. In one sentence, it is "preparing a set of algorithms and encapsulating each algorithm so that they can be exchanged ". 2) In the policy mode, the client determines under what circumstances the detailed policy role should be used. (2) 3) the policy mode only encapsulates the algorithm and provides the convenience of inserting the new algorithm into the existing system and retiring the old algorithm from the system, the policy mode does not determine when to use the algorithm. The choice of the algorithm is determined by the client. This improves the system flexibility to a certain extent, but the client needs to understand the differences between all detailed policy classes in order to select an appropriate algorithm, which is also one of the shortcomings of the Policy mode, to some extent, it is difficult to use the client.

Hguisu design pattern (18) Strategy pattern strategy (object behavior pattern) http://blog.csdn.net/hguisu/article/details/7558249


Design Mode (18) Strategy Mode strategy (object behavior type)

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.