挺有意思的看了一个例子,将不通的Algorithm 设计为不同的类,然后通过一个Context 类联系在一起。
点击(此处)折叠或打开
- package policypattern;
- interface Strategy{
- public void sort(int[] numbers);
- }
- class MyContext{
- private Strategy strategy;
- //constructor
- public MyContext(Strategy strategy){
- this.strategy= strategy;
- }
- public void arrange(int[] input){
- strategy.sort(input);
- }
- }
- class BubbleSort implements Strategy{
- @Override
- public void sort(int[] numbers){
- System.out.println("Sorting array using bubble sort strategy");
- }
- }
- class InsertionSort implements Strategy{
- @Override
- public void sort(int[] numbers){
- System.out.println("Sorting array with insertion sort strategy");
- }
- }
- class MergeSort implements Strategy{
- @Override
- public void sort(int[] numbers){
- System.out.println("Sorting array using merge sort strategy");
- }
- }
- class QuickSort implements Strategy{
- @Override
- public void sort(int[] numbers){
- System.out.println("Sorting array using quick sort strategy");
- }
- }
- public class StrategyPatternDemo {
- public static void main(String[] args){
- int[] var = {1,2,9,6,4,10};
- //provide any strategy to do the sorting
- MyContext ctx = new MyContext(new BubbleSort());
- ctx.arrange(var);
- //we can change the Strategy without changing Context class
- ctx = new MyContext(new QuickSort());
- ctx.arrange(var);
- }
- }