Design Mode learning notes-Strategy Mode

Source: Internet
Author: User

Rule Mode

The behavior pattern of an object is an algorithm that encapsulates each algorithm into an independent class with a common interface, so that they can be replaced with each other.

The policy mode allows the algorithm to change without affecting the client.

 

Policy mode is the packaging of algorithms. It separates the responsibility for using algorithms from the algorithms themselves and delegates them to different objects for management.

 

Roles involved in rule mode:

Environment role Context: Hold reference of the Strategy class

Abstract policy Role Strategy: Abstract role, which is implemented by an interface or abstract class and provides a unified algorithm interface.

Specific policy role ConcreteStrategy: Specific Algorithm Implementation

 

A class image

 

 

From the code point of view, the policy mode is quite simple and can even be avoided. below is the implementation of various classes.

First, the abstract interface Strategy

Java code

Public interface Strategy {

Public void strategyInterface ();

}

 

Next is the specific policy class. Here we implement two, just print a sentence.

Java code

Public class ConcreteStrategy implements Strategy {

@ Override

Public void strategyInterface (){

System. out. println ("first strategy ");

}

}

 

Public class ConcreteStrategy2 implements Strategy {

@ Override

Public void strategyInterface (){

System. out. println ("second strategy ");

}

}

 

In addition, it is an environment role that holds a reference to the strategy class.

Java code

Public class Context {

Private Strategy strategy;

Public Context (Strategy strategy ){

This. strategy = strategy;

}

Public void contextInterface (){

Strategy. strategyInterface ();

}

}

 

Finally, let's look at the effect of the policy model.

Java code

Public class StrategyPattern {

Public static void main (String [] args ){

Context context1 = new Context (new ConcreteStrategy ());

Context context2 = new Context (new ConcreteStrategy2 ());

Context1.contextInterface ();

Context2.contextInterface ();

}

}

 

Output result

First strategy

Second strategy

 

The above rule pattern should be the simplest. In the book, we also mention the things that need to be paid attention to when implementing the rule pattern.

1. The specific policy role has public behaviors or attributes. In this case, the above Strategy should be changed from interface to abstract class.

2. The policy mode can only use one policy object at a time, but one application may need to be associated with multiple policies. That is to say, when the application starts, the policy object should have been created to implement switching.

 

Time to use the rule mode:

1. There are many classes in the system, and the difference between them is behavior.

2. If the system needs to dynamically select several algorithms, the algorithms will be packaged.

3. The data used by the system algorithm cannot be known to the client.

4. An object has multiple behaviors and can only be implemented using multiple if... else statements.

 

Advantages and disadvantages of Rule Mode

Advantages

1. provides methods for managing related algorithm families. If inheritance is used properly, public code can be transferred to the parent class to avoid repeated code

2. The rule mode provides a method to replace the inheritance relationship.

3. Multiple condition judgment is avoided.

Disadvantages

1. The client must know all the policy classes and decide which one to use.

2. There will be many strategies (the number of objects can be reduced in the enjoy Mode)

 

The above is a simple description of the Rule mode. Many of them are also excerpted from the book. There are also many articles on the Internet about the rule mode. Below are two specific articles.

Http://www.cnblogs.com/justinw/archive/2007/02/06/641414.html

Http://www.uml.org.cn/sjms/201009092.asp

Both of them have a very step-by-step explanation process, which provides specific scenarios, how to provide optimization, and why to use the policy mode. It is very good and highly recommended.

The duck problem in the previous article is to abstract the fly behavior of ducks into interfaces and provide specific fly methods for different ducks, and the duck chooses which method to use.

The latter is a typical policy model scenario, with discounts. Similarly, different discount methods are implemented as specific policies, and the customer determines which discount method should be used.

From the perspective of different ducks (different customers) above, it also reflects a disadvantage of the Policy mode, that is, the client must know the available policies.

 

In addition to the above two examples, this example is also available in Java. the examples in awt and LayoutManager may be difficult to understand for those who have no contact with awt. in Java or C, there is a frequently used thing that also applies the rule mode, which is the Sorting Problem.

I discussed this issue with Han Shen just two days ago. java has implemented the sort method for the value type List, which everyone knows. But for the List <T> generic type, we often place non-value elements. More often, they are object sets, so the sort method is unavailable.

After careful observation, we will find that there is a static method sort (Collections <T> cols, Comparator comp) in Collections. This method is also worth our attention.

Comparator is an interface that corresponds to the abstract Strategy class Strategy in the Policy mode. Therefore, the Sorting Problem is very easy to understand in the corresponding policy mode, to implement our own sorting algorithm, we should implement our own MyComparator (corresponding to the specific policy ConcreteStrategy ). Here, Collections naturally plays the role of Context.

 

Here I would like to add an additional note. For the difference between Comparator and Comparable, we have mentioned that Comparator represents a specific policy algorithm. Comparable refers to the ability. It can be understood that objects that implement Comparable can be compared, that is, the ability to Compare classes (to implement the Compare method), while Comparator is implemented, it is just a specific comparison algorithm.

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.