Detailed explanation of the strategy pattern in Java design pattern programming _java

Source: Internet
Author: User

definition: defines a set of algorithms that encapsulate each algorithm and allow them to be interchangeable.
Type: behavior class pattern
class Diagram:

The strategy pattern is the encapsulation of the algorithm, which encapsulates a series of algorithms into the corresponding classes, and these classes implement the same interface and can be replaced by each other. In the behavior class pattern mentioned earlier, there is a pattern is also concerned about the encapsulation of the algorithm-template method mode, compared to the class diagram can be seen, the policy model and template method model is only a separate package of the context, it and template method mode is the difference between: in the Template method mode, The principal of the calling algorithm is in the abstract parent class, and in the policy pattern, the principal of the calling algorithm is encapsulated into the encapsulation class context, and the abstract policy strategy is generally an interface, intended only to define the specification, which generally does not contain logic. In fact, this is only a common implementation, and in real programming, because the various specific policy implementation classes inevitably exist between some of the same logic, in order to avoid duplicate code, we often use abstract classes to serve as the role of strategy, in the package of common code, so, in many application scenarios, In the policy mode, you will generally see the shadow of the template method pattern.

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 on the policy.
Abstract policy: Typically an interface, when duplicate logic exists in each implementation class, an abstract class is used to encapsulate this part of the common code, at which point the policy pattern looks more like a template method pattern.
Specific strategy: The specific policy role is usually performed by a set of classes that encapsulate the algorithms, which can be freely replaced as needed.

Examples of application scenarios:

Liu Bei is going to the Jiangdong to marry his wife, go before Zhuge Liang to Zhao (best man) Three an ace, say is according to the secret can solve the thorny problem, hey, also don't say, really solve the big problem, get to the end is Zhou Yu with the wife and folding soldiers, then we first see what this scene is like.

First of all, the elements of this scene: Three A coup, a Kam sac, a Zhao, clever plan is bright elder brother to, clever plan put in Kam bag, commonly known as an ace, that Zhao is a work of people, from the Kam sac out of the plan, execute, and then win. How do you represent these with Java programs?
Let's take a look at the picture first.

Three ingenious tricks are the same type of thing, so let's write an interface:

Package com.yangguangfu.strategy; 
/** 
 * * 
 @author trygf521@126.com: Fu 
 * First define a policy interface, this is Zhuge Liang old people to Zhao three an ace of the interface. 
 * * Public 
interface IStrategy { 
  //each ACE is an executable algorithm. Public 
  Void Operate (); 
 
} 


And then write three implementation classes, there are three clever tricks:

A coup: The first to Wu:

Package com.yangguangfu.strategy; 
/** 
 * * 
 @author trygf521@126.com: Fu 
 * to find Cho old help, so that Sun Quan can not kill Liu Bei. 
 * 
/public class backdoor implements IStrategy { 
 
  @Override public 
  Void Operate () { 
    System.out.println ("Find Cho old help, let Wu too to exert pressure on Sun Quan, so that Sun Quan can not kill Liu Bei ..."); 
  } 
 
 


Coup II: Please Wu too open a green light, release:

Package com.yangguangfu.strategy; 
/** 
 * * 
 @author trygf521@126.com: Fu 
 * Beg Wu too to open a green light. 
 * 
/public class Givengreenlight implements IStrategy { 
 
  @Override public 
  Void Operate () { 
    SYSTEM.OUT.PRINTLN ("Ask Wu to open a green light, release!") "); 
     
  } 
 
} 

Coup III: Neighbour rear, blocking the pursuers:

Package com.yangguangfu.strategy; 
/** 
 * * 
 @author trygf521@126.com: Fu 
 * Neighbour after the rear, blocking the pursuers. 
 * 
/public class Blackenemy implements IStrategy { 
 
  @Override public 
  Void Operate () { 
    System.out.println ("Neighbour the rear, blocking the pursuers ..."); 
 
  } 
 
 


All right, let's see, three tricks are there, there needs to be a place to put the coup ah, put the Kam bag:

Package com.yangguangfu.strategy; 
/** 
 * * 
 @author trygf521@126.com: Fu * * * * * Public 
 class context 
{ 
   
  private istrategy strategy; 
  constructor, which one do you want to use? Public context 
  (IStrategy strategy) { 
    this.strategy = strategy; 
  } 
   
  public void Operate () { 
    this.strategy.operate (); 
  } 
 
} 


Then is Zhao valiantly three a Kam bag, pull has entered the ranks of old people, but also want to marry innocent girl, color Mimi Liu Bei the father to Ruzhui, hey, also don't say, Bright elder brother's three ingenious scheme is really good, look at:

Package com.yangguangfu.strategy; 
 
public class Zhaoyun { 
 
  /** 
   * Zhao appeared, he based on Zhuge Liang to his account, and then open the coup 
  /public static void Main (string[) args) { 
    Context context; 
     
    When he arrived in Wu, he opened the first 
    System.out.println ("----------opened the first---------------" when he arrived in Wu); 
    Context = new context (new backdoor ()); 
    Context.operate ()//disassemble the execution 
    System.out.println ("\n\n\n\n\n\n\n\n\n\n\n\n\n"); 
     
    When Liu Bei reluctant, opened the second 
    System.out.println ("----------Liu Bei Reluctant, split the second---------------"); 
    Context = new Context (new Givengreenlight ()); 
    Context.operate ()//disassemble the execution 
    System.out.println ("\n\n\n\n\n\n\n\n\n\n\n\n\n"); 
     
    What about Sun Quan's little pursuers? Open the third capsule 
    System.out.println ("----------Sun Quan's little pursuers, how?" Opening the third capsule---------------"); 
    Context = new Context (new Blackenemy ()); 
    Context.operate ()//Disassemble execution 
    System.out.println ("\n\n\n\n\n\n\n\n\n\n\n\n\n"); 
  } 
 
 


Advantages and disadvantages of the strategy model
The key benefits of the policy model are:
Policy classes are free to switch between, because the policy class implements the same abstraction, so they can switch freely between them.
Easy to scale, adding a new strategy is easy for the policy model, and can be extended basically without changing the original code.
Avoid the use of multiple conditions, if you do not use the policy pattern, for all algorithms, must use conditional statements to connect, through conditional judgment to determine which algorithm to use, in the previous article we have mentioned that the use of multiple conditions to judge is often not easy to maintain.
The main disadvantages of the policy model are two:
Maintaining individual policy classes can lead to additional costs for development and may be experienced in this regard: In general, the number of policy classes is more than 5, which is more frustrating.
All policy classes must be exposed to the client (caller) because it is up to the client to decide which policy to use, so the client should know what the strategy is and understand the differences between the various policies, otherwise the consequences are serious. For example, there is a strategy pattern of the sorting algorithm, which provides a quick sort, bubble sort, and choice of sorting three algorithms, before the client uses these algorithms, is it necessary to understand the application of these three algorithms? Again for example, the client wants to use a container, has the link list realizes, also has the array realization, does the client also want to understand the link list and the group what difference? This is contrary to Dimitri law.

Applicable Scenarios
To do object-oriented design, the policy model must be very familiar, because it is essentially object-oriented inheritance and polymorphism, after reading the general code of the strategy pattern, I think, even if never heard of the strategy model, in the development process must have used it? At least in the following two situations, you can consider using the policy model,
The main logic of several classes is the same, and only slightly different in some logical algorithms and behaviors.
There are several similar behaviors, or algorithms, where the client needs to decide dynamically which one to use, and the policy pattern can be used to encapsulate these algorithms for client invocation.
The strategy pattern is a kind of simple commonly used pattern, we in the development, will often intentionally or unintentionally use it, generally speaking, the strategy pattern does not use alone, with the template method pattern, the factory pattern and so on mixes uses the situation to be more.

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.