本文共 1377 字,大约阅读时间需要 4 分钟。
三个角色:
使用环境角色:
抽象策略角色: 具体策略角色:UseContext : TreeSet
IStrategy : ComparatorTreeSettreeSet = new TreeSet (new Comparator () { @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); }
转载地址:http://weaji.baihongyu.com/