(12) Strategy mode

Source: Internet
Author: User



definition: Define a set of algorithms that encapsulate each algorithm and allow them to be interchanged.

Type: behavior class mode

Class Diagram:


The policy pattern is the encapsulation of the algorithm, which encapsulates a series of algorithms into corresponding classes, and these classes implement the same interface, which can be replaced by each other. In the behavior class pattern, there is a pattern is also concerned about the encapsulation of the algorithm-template method mode, the control class diagram can be seen, the difference between the policy mode and the template method mode is only a separate wrapper class Context, it differs from the template method pattern is: In the template method mode, The principal of the calling algorithm is in the abstract parent class, and in the policy mode, the body of the calling algorithm is encapsulated in the wrapper class context , the abstract policy strategy is generally an interface, The purpose is simply to define the specification, which generally does not contain logic. In fact, this is only a generic implementation, and in actual programming, because there are inevitably some of the same logic between specific policy implementation classes, in order to avoid duplication of code, we often use abstract classes to assume the role of strategy , in which to encapsulate the common code, therefore, in many application scenarios, the shadow of the template method pattern is generally seen in the strategy mode.

Structure of the policy pattern

  • Encapsulation class: also called context, the policy is encapsulated two times to avoid the direct call of the high-level module to the policy.

  • abstract strategy: typically an interface, when there are repetitive logic in each implementation class, use an abstract class to encapsulate this part of the common code, at which point the policy pattern looks more like a template method pattern.

  • specific policy: a specific policy role is typically assumed by a set of classes that encapsulate the algorithm, which can be freely replaced as needed.


Policy Mode Code implementation

Interface IStrategy {public    void dosomething ();}
Class ConcreteStrategy1 implements IStrategy {public    void dosomething () {       System.out.println ("Specific Strategy 1");}    }
Class ConcreteStrategy2 implements IStrategy {public    void dosomething () {       System.out.println ("Specific Strategy 2");}    }
Class Context {    private istrategy strategy;        Public Context (IStrategy strategy) {       this.strategy = strategy;    }        public void Execute () {       strategy.dosomething ();    }}
public class Client {public    static void Main (string[] args) {       context context;       SYSTEM.OUT.PRINTLN ("-----Execution Strategy 1-----");       Context = new Context (new ConcreteStrategy1 ());       Context.execute ();        SYSTEM.OUT.PRINTLN ("-----Execution Strategy 2-----");       Context = new Context (new ConcreteStrategy2 ());       Context.execute ();    }}

Advantages and disadvantages of the strategy model

The key benefits of the strategy model are:

  • The policy classes are free to switch between them, and because the policy classes are implemented from the same abstraction, they are free to switch between them.

  • Easy to scale, adding a new strategy to the strategy model is very easy, basically can be extended without changing the original code.

  • Avoid using multiple conditions, if you do not use the policy mode, for all the algorithms, you must use conditional statements to connect, through conditional judgment to decide which algorithm to use, in the previous article we have mentioned that the use of multiple criteria to judge is not often easy to maintain.

    There are two main disadvantages of the strategy model:

    • Maintaining individual policy classes can add additional overhead to development, and you may have experience in this area: In general, the number of policy classes is more than 5 , which makes it more of a headache.

    • All policy classes must be exposed to the client (caller), since it is up to the client to decide which policy to use, so the client should know what the policy is and understand the differences between the various policies, otherwise the consequences are serious. For example, there is a strategy pattern for sorting algorithms that provides three algorithms for fast sorting, bubbling sorting, and selection sorting, before the client can use these algorithms, is it necessary to understand the applicability of these three algorithms first? For example, the client to use a container, there are linked list implementation, there is an array implementation, the client is not to understand the difference between the list and arrays? This is contrary to the Dimitri law.

Applicable scenarios

Do object-oriented design, must be very familiar with the strategy mode, because it is essentially object-oriented inheritance and polymorphism, after reading the general code of the policy mode, I think, even if I have never heard of the strategy mode, in the development process must have used it? At least in the following two scenarios, you may consider using the policy model,

The main logic of several classes is the same, only a slight difference in the algorithm and behavior of the partial logic.

There are several similar behaviors, or algorithms, in which the client needs to dynamically decide which one to use, then the policy pattern can be used to encapsulate these algorithms for client invocation.

Strategy mode is a simple and common pattern, we often use it intentionally or unintentionally when we develop it, in general, the strategy mode will not be used alone, compared with the template method mode, Factory mode and other mixed use of the situation is more.

(12) Strategy mode

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.