Strategy pattern also known as Policy Pattern. 

挺有意思的看了一个例子,将不通的Algorithm 设计为不同的类,然后通过一个Context 类联系在一起。


点击(此处)折叠或打开

  1. package policypattern;

  2. interface Strategy{
  3.     public void sort(int[] numbers);
  4. }

  5. class MyContext{
  6.     private Strategy strategy;

  7.     //constructor
  8.     public MyContext(Strategy strategy){
  9.         this.strategy= strategy;
  10.     }

  11.     public void arrange(int[] input){
  12.         strategy.sort(input);
  13.     }
  14. }

  15. class BubbleSort implements Strategy{
  16.     @Override
  17.     public void sort(int[] numbers){
  18.         System.out.println("Sorting array using bubble sort strategy");
  19.     }
  20. }

  21. class InsertionSort implements Strategy{

  22.     @Override
  23.     public void sort(int[] numbers){
  24.         System.out.println("Sorting array with insertion sort strategy");
  25.     }
  26. }


  27. class MergeSort implements Strategy{
  28.     @Override
  29.     public void sort(int[] numbers){
  30.         System.out.println("Sorting array using merge sort strategy");
  31.     }
  32. }

  33. class QuickSort implements Strategy{
  34.     @Override
  35.     public void sort(int[] numbers){
  36.         System.out.println("Sorting array using quick sort strategy");
  37.     }
  38. }



  39. public class StrategyPatternDemo {
  40.     public static void main(String[] args){
  41.         int[] var = {1,2,9,6,4,10};

  42.         //provide any strategy to do the sorting
  43.         MyContext ctx = new MyContext(new BubbleSort());
  44.         ctx.arrange(var);

  45.         //we can change the Strategy without changing Context class
  46.         ctx = new MyContext(new QuickSort());
  47.         ctx.arrange(var);
  48.     }
  49. }

10-12 11:04
查看更多