Policy mode (strategy pattern)

Source: Internet
Author: User

Policy patterns are well applied in TreeSet and TreeMap in the Java collection, and we can implement the comparator interface implementation CompareTo () method to define our own collation, and then through TreeSet, TreeMap constructs an instance of implementing the interface, the order in the map is our custom order. We can completely define our own rules and use them very conveniently. So, what is the strategy model?

Policy pattern Definition: Defines a set of algorithms that encapsulate each algorithm and make it possible to convert between them. The policy pattern enables these algorithms to change independently of each other when called by the client.

The policy mode consists of:

1. Abstract policy role: A policy class, usually implemented by an abstract class or interface.

2. Specific strategy roles: wrapping the relevant algorithms and behaviors.

3. Environment role: holds a reference to a policy class for eventual invocation to the client.

The design principle of the strategy mode;

1. Package Changes

2. Programming with interfaces

Implementation of the policy pattern:

1. Encapsulate each set of algorithms in a separate class with a common interface so that different policies can replace each other

2. The algorithm can be changed without affecting the client, separating the behavior from the environment.

3. The Environment class is responsible for maintaining and querying behavior classes, and various algorithms are provided in the specific strategy

Look at the text to see blindfolded, give a concrete example, what example? Think of our data structures in various sorts, what bubble sort, quick sort, heap sort ..., they complete the function is the same, but the sorting algorithm is different. We can look at the different strategies of sorting.

First, we define our abstract strategy:

/**@author*/Publicinterface  strategy        {  Public void sort (int[] array);}
View Code

Define the specific strategy, where three strategies are implemented, namely, quick sorting, heap sorting, merge sort.

Quick Sort Policy code:

 Public classQuickSortImplementsstrategy{@Override Public voidSortint[] Array) {qpsort (array,0,array.length-1); }        Private voidQpsort (intArray[],intLowintHigh ) {        intpos = Qkpass (array, low, high);//produces the first determined number in the middle        if(Low <High ) {Qpsort (array, low, POS-1);//leftQpsort (Array, pos + 1, high);//Right        }    }    Private  intQkpass (intA[],intLowintHigh ) {        intx =A[low];  while(Low <High ) {             while(Low < High && A[high] >x) { high--; }            if(Low <High ) {A[low]=A[high]; Low++; }             while(Low < High && A[low] <x) { Low++; }            if(Low <High ) {A[high]=A[low]; High--; }} A[low]=x; returnLow ; }    }
View Code

Heap Sort Policy code:

 Public classHeapsortImplementsStrategy {@Override Public voidSortint[] Array)    {heapsort (array,array.length); }    Private voidHeapsort (intA[],intlength) {Crtheap (A, length);//Create Dagen         for(inti = length-1; i > 0; i--) {            intb = a[0]; a[0] = A[i];//stack top and tail swapA[i]=b; Sift (A,0, I-1);//make r[0...i-1] into a heap        }    }    /*** Build the first heap * *@paramA * is a sorted array *@paramLength * Number of array lengths*/    Private voidCrtheap (intA[],intlength) {        intn = length-1; //build the heap and start the heap filtering from the first N/2 record         for(inti = N/2; I >= 0; i--) {Sift (A, I, N); }    }    /**     *      * @paramR * Array *@paramk * denotes a complete binary tree with R[k] as root, adjusting r[k], so that r[k...m] satisfies the nature of Dagen *@paramm * Stack tail element subscript*/    Private voidSiftintR[],intKintm) {inttemp = R[k];//temporary stub record        inti = k;//record the subscript of the initial root        intj = i * 2 + 1;//the left child of the root, since the subscript starts from 0         while(J <=m) {//If there is a right subtree, and the key for the right child root is large, filter along the right branch, otherwise along the left branch. Because the goal is to find the biggest element            if(J < m && R[j] < R[j + 1]) {J= j + 1; }            if(Temp >=R[j]) {                 Break;//End Filter            }            Else{R[i]= R[j];//Move Upi = j;//new definition of root subscriptj = J * 2 + 1;//Continue filtering}} R[i]= temp;//move R[k] to the appropriate location    }}
View Code

Merge sort Policy code:

 Public classMergeSortImplementsstrategy{@Override Public voidSortint[] Array) {        int[] temp =New int[Array.Length]; Msort (Array,0,array.length-1, temp); }        /**     *      * @paramR1 waiting for sorted array *@paramLow *@paramHigh *@paramR3 Place R1 sorted results in R3 R1[low...high],r3[low...high]*/    Private voidMsort (intR1[],intLowintHighintr3[]) {                                if(Low <High ) {            intMid = (low + high)/2; //merge sort to split, together to doMsort (R1,LOW,MID,R3); Msort (R1,mid+1, HIGH,R3);        Merge (R1,low, Mid, High, R3); }            }        Private voidMergeintR1[],intLowintMidintHighintr2[]) {                inti =Low ; intj = Mid + 1; intK = 0;  while(I <=mid && J <=High ) {                        if(R1[i] <=R1[j]) {R2[k]=R1[i]; I++; }            Else{R2[k]=R1[j]; J++; } k++; }                 while(I <=mid) {R2[k]=R1[i]; I++; K++; }                 while(J <=High ) {R2[k]=R1[j]; J++; K++; }                 for(intm = 0; M < k;m++) {R1[low+ M] =R2[m]; }    }}
View Code

Define the Environment class:

 Public classEnvironment {PrivateStrategy strategy;//a reference to a policy class         PublicEnvironment (Strategy strategy) { This. Strategy =strategy; }        //used to set a different policy     Public voidSetstrategy (Strategy strategy) { This. Strategy =strategy; }        //the ability to implement sorting     Public voidSortintarray[])    {strategy.sort (array); }    }
View Code

Finally, define the client class:

 Public classClient { Public Static voidMain (string[] args) {int[] Array1 =New int[]{48,62,35,77,55,14,35,98}; int[] Array2 =New int[]{48,62,35,77,55,14,35,98}; int[] Array3 =New int[]{48,62,35,77,55,14,35,98}; //using heap sorting policiesEnvironment env =NewEnvironment (Newheapsort ());        Env.sort (array1); System.out.println ("Use heap sort array1:");                Print (array1); //using the Quick sort policyEnv.setstrategy (NewQuickSort ());        Env.sort (array2); System.out.println ("Use Quick sort array2:");                Print (array2); //using the merge sort policyEnv.setstrategy (Newmergesort ());        Env.sort (ARRAY3); System.out.println ("Use Merge to sort array3:");            Print (ARRAY3); }        Static voidPrintint[] Array) {         for(inti = 0; i < Array.Length; i++) {System.out.print (Array[i]+ "\ T");        } System.out.println (); System.out.println ("---------------------------------"); }}
View Code

The results of the operation are as follows:

The ability to sort three arrays using different sorting strategies has been implemented, the program is very flexible, and what strategy we want to use to implement the ordering can be decided by ourselves (via the Environment.serstrategy (XXX) method).

The Environment class in the program does not know and does not need to control how the sort is implemented, it simply holds a reference to a specific policy class, and then invokes the method of the specific policy class.

The strategy model is easy to use, but it has its drawbacks:

1. The client must know all the policy classes and decide for themselves which policy class to use.

2. Resulting in a lot of strategy classes, each of the different strategies requires a strategy class to implement.

For the 1th, it is obvious that our client class must know what the specific policy class is when using the policy, and the Environment.serstrategy (XXX) method needs to know.

For the 2nd, there are 3 policy classes defined in 3, and there are many classes if there are many strategies.

 

Reference: Santhiya Garden Teaching Video

Policy mode (strategy pattern)

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.