Strategy Mode
Policy model is intended for a set of algorithms, each algorithm is encapsulated into a separate class have a common interface, so that that they can replace each other. Changes in the policy mode makes the algorithm can not affect the client's situation.
Structure of the strategy pattern
Strategy Mode is a package of algorithms, and the algorithm is the responsibility of using the algorithm itself apart. The strategy pattern is usually a series of algorithms to package a series of strategies inside the class, as a subclass of the abstract Policy class.
Strategy Mode involves three characters:
1, the role of the environment
Strategy Strategy holds a reference to
2, abstract strategy role
This is an abstract role, usually an interface or abstract class implemented by, this role gives specific strategies required for all classes Interface
3, the role of specific strategies
Packing a correlation algorithm or behavior
Strategy mode practical application scenarios - fault-tolerant recovery mechanism
Fault-tolerant recovery mechanism is very common in application development functions. So what is the fault-tolerant restore it? Simply put, it is this: when the program is run, under normal circumstances should be done in a certain way, if in some way to do an error occurs, the system does not collapse, nor can not continue to run this down, and It is the ability to tolerate mistakes, not only can tolerate running errors, it also provides an alternative after the error, which is the recovery mechanism to replace the function of the normal execution of the program continues to run down.
For example the actual point of it, in such a system, all the operations should have a log, but also need to have the log management interface, in this case it will usually log in a database, to facilitate the subsequent management, but when logging into the database, an error may occur, for example, temporarily Rom database, and then the first record in the file inside, and then at the right time to record in the file and then transcribed into a database.
For such design features, you can use the Strategy pattern, the log records to the database and log files as two recording log to the policy, and then dynamically switch as needed during operation.
Examples
1. Define log policy interfaces
1 public interface LogStrategy { 2 3 public void log(String msg); 4 5 }
2. Implement log policy interfaces
1) records to the database
. 1 public class dblog the implements LogStrategy { 2 . 3 public void log (String MSG) { . 4 . 5 System.out.println ( "Now the '" + msg + "' record to the database" ); . 6 . 7 } . 8 . 9 }
2) records to a file
. 1 public class filelog the implements LogStrategy { 2 . 3 public void log (String MSG) { . 4 . 5 System.out.println ( "Now the '" + msg + "' to a file" ); . 6 . 7 } . 8 . 9 }
3) Next, define the context of use of these strategies, this is noted that selection of a particular strategy algorithm implemented in the context of which, the client is not required to specify a specific strategy algorithm, the following sample code:
1 public class LogContext { 2 3 public void log(String msg) { 4 5 LogStrategy strategy = new DbLog(); 6 try { 7 strategy .log(msg); 8 } catch(Exception e) { 9 // 出错,记录到文件 10 strategy = new FileLog(); 11 strategy.log(msg); 12 } 13 } 14 }
4. Summary
By the example above, you will see a simple application strategy mode, but also the way to look at the design and realization of fundamental fault-tolerant recovery mechanism. In practical applications, the need to design fault-tolerant recovery system general requirements are high, the application will be more complicated, but the basic idea is the same.
Java interfaces in strategy interfaces -Comparator
For example Collections There is a sort method, because the collection elements inside there may be complex objects, composite objects is not as primitive data types can be sorted according to size, how to sort the composite object? Based on consideration of this issue, Java required if the composite object is defined to have a sort feature, you implement the Comparable interface or Comparator interface itself, look at the overloaded methods with a sort of Comparator:
1 public static <T> void sort(List<T> list, Comparator<? super T> c) { 2 Object[] a = list.toArray(); 3 Arrays.sort(a, (Comparator)c); 4 ListIterator i = list.listIterator(); 5 for (int j=0; j<a.length; j++) { 6 i.next(); 7 i.set(a[j]); 8 } 9 }
Look at line 3:
1 public static <T> void sort(T[] a, Comparator<? super T> c) { 2 T[] aux = (T[])a.clone(); 3 if (c==null) 4 mergeSort(aux, a, 0, a.length, 0); 5 else 6 mergeSort(aux, a, 0, a.length, 0, c); 7 }
Look again at the Line 6:
1 private static void mergeSort(Object[] src, 2 Object[] dest, 3 int low, int high, int off, 4 Comparator c) { 5 int length = high - low; 6 7 // Insertion sort on smallest arrays 8 if (length < INSERTIONSORT_THRESHOLD) { 9 for (int i=low; i<high; i++) 10 for (int j=i; j>low && c.compare(dest[j-1], dest[j])>0; j--) 11 swap(dest, j, j-1); 12 return; 13 } 14 15 // Recursively sort halves of dest into src 16 int destLow = low; 17 int destHigh = high; 18 low += off; 19 high += off; 20 int mid = (low + high) >>> 1; 21 mergeSort(dest, src, low, mid, -off, c); 22 mergeSort(dest, src, mid, high, -off, c); 23 24 // If list is already sorted, just copy from src to dest. This is an 25 // optimization that results in faster sorts for nearly ordered lists. 26 if (c.compare(src[mid-1], src[mid]) <= 0) { 27 System.arraycopy(src, low, dest, destLow, length); 28 return; 29 } 30 31 // Merge sorted halves (now in src) into dest 32 for(int i = destLow, p = low, q = mid; i < destHigh; i++) { 33 if (q >= high || p < mid && c.compare(src[p], src[q]) <= 0) 34 dest[i] = src[p++]; 35 else 36 dest[i] = src[q++]; 37 } 38 }
Line 10 returns the result of the decision whether to swap (exchange) compare Comparator interface method according to the class.
This is the strategy pattern, we can pass in different Comparator implementation class as a comparison of different strategies to the sort method of Collections. Comparison of different strategies for the same collection, may produce different results will be sorted.
Strategy mode advantages and disadvantages
advantage
1, to avoid multiple conditions if ... else if ... else statement, the statement is not easy to maintain multiple condition
2, the policy mode provides management-related algorithms cluster approach, the proper use of public inheritance can put code to the parent, thus avoiding code duplication
Shortcoming
1, the client must know all the policy class, and to decide which strategy to use, which means that the client must understand the difference between these algorithms, in order to select the appropriate algorithm
2, if a lot of alternative strategies, the object will be a lot of data