1.静态主调类
package com;
import java.util.List;
import java.util.ArrayList;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
List input = new ArrayList();
input.add(8);
input.add(28);
input.add(4);
input.add(7);
input.add(2);
input.add(5);
input.add(6);
input.add(9);
Sorter sorter = new Sorter(new SortBin());
sorter.sort(input);
sorter = new Sorter(new SortBubble());
sorter.sort(input);
sorter = new Sorter(new SortHeap());
sorter.sort(input);
}
}
2.排序类
package com;
import java.util.List;
public class Sorter {
private SortStrategy strategy;
public Sorter(SortStrategy strategy) {
super();
if(strategy == null)
strategy = new SortBubble();
this.strategy = strategy;
}
public void sort(List list)
{
this.strategy.sort(list);
}
}
3.策略管理接口类
package com;
import java.util.List;
public interface SortStrategy {
public void sort(List list);
}
4.排序算法类
package com;
import java.util.List;
public class SortBin implements SortStrategy {
@Override
public void sort(List list) {
// TODO Auto-generated method stub
System.out.print("This is bin sort method \n");
}
}
package com;
import java.util.List;
public class SortBubble implements SortStrategy {
@Override
public void sort(List list) {
// TODO Auto-generated method stub
System.out.print("This is Bubble sort method!\n");
}
}
package com;
import java.util.List;
public class SortHeap implements SortStrategy {
@Override
public void sort(List list) {
// TODO Auto-generated method stub
System.out.print("This is Heap sort method! \n");
}
}
5.总结
应用场景:在涉及到一系列的算法的时候,可以考虑采用策略模式把一个个算法封装成单独的类。
通过注入不同的算法策略类,从而使得使用者得到不同的算法结果。
阅读(1769) | 评论(0) | 转发(0) |