Rule mode, java rule Mode
Definition: It is the packaging of algorithms. It separates the responsibility for using algorithms from the algorithms themselves and delegates them to different objects for Management. The policy mode Usually packs a series of algorithms into a series of policy classes, as a subtype of the abstract policy type, it is: "prepare a set of algorithms and encapsulate each algorithm so that they can be exchanged ";
Intention: For a group of algorithms, each algorithm is encapsulated 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;
1 public class StrategyDemo {2 public static void main (String [] args) {3 int [] array = {, 64, 88, 28 }; 4 ISort bubbleSort = new BubbleSort (); 5 Context con = new Context (bubbleSort); 6 con. sort (array); 7 con. printArray (array); 8} 9} 10 11 class Context {12 private ISort iSort = null; 13 public Context (ISort iSort) 14 {15 this. iSort = iSort; 16} 17 18 public void sort (int [] array) {19 // hand it over to a specific policy object to help 20 iSo Rt. sort (array); 21} 22 // print the content in the array 23 public void printArray (int [] array) {24 for (int I = 0; I <array. length; I ++) 25 {26 System. out. print (array [I] + ""); 27} 28} 29} 30 31 interface ISort {32 public void sort (int [] array ); 33} 34 35 // encapsulation of the Bubble sorting method 36 class BubbleSort implements ISort {37 public void sort (int [] array) {38 System. out. println ("Bubble Sorting"); 39 for (int I = 0; I <array. length-1; I ++) {40 for (int j = 0; j <array. length-1- I; j ++) {41 if (array [j]> array [j + 1]) {42 int temp = array [j]; 43 array [j] = array [j + 1]; 44 array [j + 1] = temp; 45} 46} 47} 48} 49} 50 51 // The selection sorting method 52 class SelectSort implements ISort {53 public void sort (int [] array) {54 System. out. println ("select sorting method"); 55 int min = 0; 56 for (int I = 0; I <array. length; I ++) {57 min = I; 58 for (int j = I + 1; j <array. length; j ++) {59 if (array [min]> array [j]) {60 min = j; 61} 62} 63 if (I! = Min) {64 int temp = array [I]; 65 array [I] = array [min]; 66 array [min] = temp; 67} 68} 69} 70}