[Switch] 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 this function. Such as search and sorting. A common method is hard coding in a class. To provide multiple search algorithms, you can write these algorithms into a class, multiple methods are provided in this class. 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 condition judgment statements for selection. Both of these methods can be called hard encoding. 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 on the client, this approach is not desirable, it 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 a horizontal or vertical arrangement is used based on the user's "skin" preferences. Colleagues can flexibly Add the display style of the menu.

Example 2: traveling: We can consider several strategies: 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 in each method.


2. Problem


How can we separate algorithms from objects so that they can change independently of customers who use them?


3. Solution

Rule mode: SetA series of algorithms, encapsulate each algorithm, and make them replace each other. 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 only 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 to allow strategy to access its data.
Abstract strategy: defines the public interfaces of all supported algorithms. Context uses this interface to call a concretestrategy-defined algorithm.
Concretestrategy: a specific 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 another 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, in addition, algorithms cannot be dynamically changed. Finally, you get a bunch of related classes. The only difference between them is the algorithm or behavior they use. Encapsulate an algorithm in an independent strategy class so that you can 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 another option other than the action needed to select with the condition statement. When different behaviors are stacked in a class, it is 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 different time/space trade-offs.

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 specific implementation problems 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 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 any of the information! This means that sometimes context will create and initialize some parameters that will never be used. If this problem exists, the closer coupling between strategy and context is required.
3) The policy mode will generate many policy classes: You can use the enjoy mode to reduce the number of objects to a certain extent. Increases the number of objects. strategy increases the number of objects in an application. Sometimes you can implement strategy as a stateless object shared by each context to reduce this sales. 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:


Code implementation:

[PHP]View Plain Copy print?
  1. <? PHP
  2. /**
  3. * Rule Mode
  4. * Define a series of algorithms, encapsulate each algorithm, and make them replaceable. This mode allows algorithms to change independently of customers who use it.
  5. *
  6. */
  7. /**
  8. * Travel
  9. *
  10. *
  11. */
  12. Interface travelstrategy {
  13. Public Function travelalgorithm ();
  14. }
  15. /**
  16. * Specific strategy (concretestrategy) 1: Fly
  17. */
  18. Class airplanelstrategy implements travelstrategy {
  19. Public Function travelalgorithm (){
  20. Echo "travel by airplain", "<br> \ r \ n ";
  21. }
  22. }
  23. /**
  24. * Specific strategy class (concretestrategy) 2: train ride
  25. */
  26. Class trainstrategy implements travelstrategy {
  27. Public Function travelalgorithm (){
  28. Echo "travel by train", "<br> \ r \ n ";
  29. }
  30. }
  31. /**
  32. * Specific strategy class (concretestrategy) 3: Cycling
  33. */
  34. Class bicyclestrategy implements travelstrategy {
  35. Public Function travelalgorithm (){
  36. Echo "maid", "<br> \ r \ n ";
  37. }
  38. }
  39. /**
  40. *
  41. * Context: uses a concretestrategy object for configuration. Maintain a reference to the strategy object. You can define an interface to allow strategy to access its data.
  42. * Algorithm solution class:
  43. */
  44. Class personcontext {
  45. Private $ _ strategy = NULL;
  46. Public Function _ construct (travelstrategy $ travel ){
  47. $ This-> _ strategy = $ travel;
  48. }
  49. /**
  50. * Travel
  51. */
  52. Public Function settravelstrategy (travelstrategy $ travel ){
  53. $ This-> _ strategy = $ travel;
  54. }
  55. /**
  56. * Travel
  57. */
  58. Public Function travel (){
  59. Return $ this-> _ strategy-> travelalgorithm ();
  60. }
  61. }
  62. // Travel by train
  63. $ Person = new personcontext (New trainstrategy ());
  64. $ Person-> travel ();
  65. // Change the bicycle ride
  66. $ Person-> settravelstrategy (New bicyclestrategy ());
  67. $ Person-> travel ();
  68. ?>


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. You can select bubble sort or insert sort as needed,

You can also flexibly add new sorting algorithms.

9. Other related models

1) status Mode

The rule mode is very similar to many other design modes. The biggest difference between the rule mode and the state mode is that the rule mode only needs to be executed once, while the state mode constantly changes the execution mode as the instance parameters (the status of the object instance) change. In other words, the policy mode is only in

When the object is initialized, the execution 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 of the Policy mode selects a specific strategy class, and the specific strategy class does not need to care about the environment class. The environment of the state mode needs to be put into a specific 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 specific policy is selected. When using the status mode, the client does not need to care about the specific status. The environment status is automatically converted according to user operations .? If a class object in the system has multiple states, the behavior varies under different States, and the status mode can be used for switching between these States; if a row of a class in the system has multiple implementation methods, and these implementation methods can be swapped, the policy mode is used.

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 specific users.
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.

Using the travel example we 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 on their own (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 builds a specific solution instead of you (the factory buys train tickets instead of you ).

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 (New trainstrategy () instances. A specific instance is passed.
In the factory mode, you only need to tell which kind of trip is needed. Instead of passing a specific instance, You need to identify it (the travel plan identifier ).


10. Summary and Analysis

1) The policy mode is a design mode that is easy to understand and use. The policy mode is an encapsulation of the algorithm. It separates the responsibility of the algorithm from 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 a word, it is "preparing a set of algorithms and encapsulating each algorithm to make them interchangeable ". 2) In the policy mode, the client determines under what circumstances the specific policy role should be used. (2) 3) the policy mode only encapsulates algorithms to facilitate insertion of new algorithms into existing systems and retirement of old algorithms from the system, the policy mode does not determine when to use the algorithm. The algorithm selection is determined by the client. This improves the system flexibility to a certain extent, but the client needs to understand the differences between all specific policy classes in order to select an appropriate algorithm, which is also one of the disadvantages of the Policy mode, to some extent, it increases the difficulty of using the client.

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

[Switch] 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.