Java design mode 6: Policy mode

Source: Internet
Author: User

Policy mode

The intent of the policy pattern is to encapsulate each algorithm in a separate class with a common interface for a set of algorithms, so that they can be replaced with each other. The policy pattern allows the algorithm to change without affecting the client.

Structure of the policy pattern

The strategy pattern is the wrapper over the algorithm , which separates the responsibility of using the algorithm and the algorithm itself. The strategy pattern is usually to wrap a series of algorithms into a series of policy classes, as subclasses of an abstract policy class.

The policy model involves three roles:

1. Environmental role

Hold a reference to a policy strategy

2. Abstract policy role

This is an abstract role, usually implemented by an interface or abstract class that gives the interfaces required for all specific policy classes

3. Specific policy roles

Wrapping a related algorithm or behavior

Example of a policy pattern

There is an abstract policy interface:

 Public Interface strategy{    publicvoid  usestrategy ();}

Two specific strategies are implemented:

 Public class Implements strategy{    publicvoid  usestrategy ()    {        System.out.println (" Strategya.usestrategy () ");}    }
 Public class Implements strategy{    publicvoid  usestrategy ()    {        System.out.println ( "Strategyb.usestrategy ()");}    }

A class holds a reference to a policy:

 Public class context{    private  strategy strategy;          Public Context (Strategy strategy)    {        this. Strategy = strategy;    }           Public void Strategymethod ()    {        strategy.usestrategy ();    }}

Where you call this class, you can decide which strategy to use in your own way:

 Public class testmain{    publicstaticvoid  main (string[] args)    {          New  Strategya ();         New strategyb ();                 New Context (Strategya);        Context.strategymethod ();         New Context (STRATEGYB);        Context.strategymethod ();    }}

Usage Scenarios for Policy mode

Give me a practical example. If there is a shopping system, when the user pays, there will be a lot of scenes, according to the different circumstances of users to calculate the amount of different users to pay, this time the most intuitive approach is:

On the inside of the payment write n many if...else If...else, judge the user's scene, calculate the user payment amount according to the scene.

This design clearly violates the opening and shutting principle. Opening and closing principle of "closed" refers to the modification is closed, but if there are several more algorithms, then you must modify the payment class again.

In this way, you can use the policy mode. In the payment class, there is a reference to a payment interface, and each time a specific strategy is introduced according to the different scenarios. For example, to use the S0 algorithm in Class A, a S0 strategy is passed in, and in class B the S1 algorithm is used to pass in a S1 algorithm. No need to put judgment in the payment class, the code is more readable and maintainable. Payment This class can even generate a. class file directly in a jar package for invocation.

Application and interpretation of strategy mode in Java

The application of the policy mode in Java, this is too obvious, because the comparator, comparable these two interfaces is simply for the strategy model of the birth. The difference between comparable and comparator in the article, detailed the use of comparator. For example, there is a sort method in collections, because the elements inside the collection are likely to be compound objects, and the composite objects are not like the basic data types, and can be sorted by size, how are the compounds sorted? Therefore, Java requires that if the defined compound object has a sort function, it implements the comparable interface itself:

1  Public Static<textendscomparable<?SuperT>>voidSort (list<t>list) {2Object[] A =List.toarray ();3 Arrays.sort (a);4listiterator<t> i =list.listiterator ();5      for(intj=0; j<a.length; J + +) {6 I.next ();7 I.set ((T) a[j]);8     }9}

The Sort method of line 3rd follows:

1  Public Static void sort (object[] a) {2         object[] aux = (object[]) a.clone (); 3         MergeSort (aux, A, 0, a.length, 0); 4     }

The MergeSort method in line 3rd is obvious:

1 Private Static voidmergesort (object[] src,2 object[] dest,3                   intLow ,4                   intHigh ,5                   intoff) {6     intLength = high-Low ;7 8     //insertion sort on smallest arrays9         if(Length <insertionsort_threshold) {Ten              for(intI=low; i) One                  for(intJ=i; J>low && A((comparable) dest[j-1]). CompareTo (Dest[j]) >0; j--) -Swap (dest, J, J-1); -             return; the         } -  -         //recursively sort halves of dest into SRC -         intDestlow =Low ; +         intDesthigh =High ; -Low + =off; +High + +off; A         intMid = (low + high) >>> 1; atMergeSort (dest, SRC, Low, mid,-off); -MergeSort (dest, SRC, Mid, high,-off); -  -         //If list is already sorted, just copy from Src to dest. this was an -         //optimization that results in faster sorts for nearly ordered lists. -         if(((comparable) src[mid-1]). CompareTo (Src[mid]) <= 0) { in system.arraycopy (src, Low, dest, destlow, length); -             return; to         } +  -         //Merge sorted halves (now in SRC) to dest the          for(inti = destlow, p = low, q = mid; i < Desthigh; i++) { *             if(q >= High | | P < MID && ((comparable) src[p]). CompareTo (Src[q]) <=0) $Dest[i] = src[p++];Panax Notoginseng             Else -Dest[i] = src[q++]; the         } +}

Looking at line 12th, each order determines whether the swap (swap) is based on the results of CompareTo.

Comparator interface Applications There are many, collections inside there is a sort of overloaded method, you can pass in a comparator subclass:

 Public Static void Super T> c) {    = list.toarray ();    Arrays.sort (A, (Comparator) c);     = list.listiterator ();      for (int j=0; j<a.length; j + +) {        i.next ();        I.set (A[j]);    }    }

Collections will sort the collection according to the policy of the specific comparator.

Recognize strategy patterns

It should be understood that the focus of the strategy pattern is not how to implement the algorithm (just as the focus of the factory pattern is not how to produce a specific subclass in the factory), but how to organize, invoke these algorithms, so that the program structure more flexible, with better maintainability and extensibility.

A big feature of the strategy model is the equality of the strategy algorithms . For a series of specific strategy algorithms, everyone's position is exactly the same, because of this equality, each algorithm can be replaced each other.

During runtime, only one specific policy implementation object can be implemented at a time, although it is possible to dynamically switch between different policies.

Advantages and disadvantages of the strategy model

Advantages

1, avoid the multiple conditions If...else if...else statement, multi-conditional statements are not easy to maintain

2, the Strategy mode provides the method to manage the related algorithm cluster, the proper use inheritance can move the common code to the Frelien, thus avoids the code duplication.

Disadvantages

1. The client must know all the policy classes and decide which policy to use, which means that the client must understand the differences between the algorithms in order to select the appropriate algorithm

2, if there are many alternative strategies, the data of the object will be many

Java design mode 6: Policy mode

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.