一、类图:
三个角色:
使用环境角色:
抽象策略角色:
具体策略角色:
二、举例:例如:TreeSet中:
UseContext : TreeSet
IStrategy : Comparator
TreeSet<Integer> treeSet = new TreeSet<Integer>(new Comparator<Integer>() {
@Override
public int compare(Integer num1, Integer num2) {
if(num1 > num2){
return 1;
}else {
return 0;
}
}
});
三、使用策略模式
//
public interface ICountStrategy{
int count(int num1, int num2);
}
//
public class CountContext{
private ICountStrategy mICountStrategy;
CountContext(ICountStrategy iCountStrategy){
mICountStrategy = iCountStrategy;
}
public int count(int num1, int num2){
return mICountStrategy.count(num1, num2);
}
}
//
public class AddStrategy implements ICountStrategy{
@Override
public int count(int num1, int num2) {
return num1 + num2;
}
}
//
public class SubtractStrategy implements ICountStrategy{
@Override
public int count(int num1, int num2) {
return num1 - num2;
}
}
//
public void test(){
CountContext countContext = new CountContext(new AddStrategy());
int result = countContext.count(1, 3);
}