设计模式之--策略模式
??????????
?
??????????????参与者
????????????? Strategy:定义所有支持的算法的公共接口。
????????????? Context:用一个ConcreteStrategy对象来配置。 维护一个对Strategy对象的引用。 可定义一个接口来让Stategy访问它的数据。
????????????? ConcreteStrategy: 以Strategy接口实现某具体算法。
????????????? 协作方法:
??????????????Strategy and Context interact to implement the chosen algorithm A context forwards requests from its clients to its strategy??
??????????????例如:
????????????? public class Context {
?????????????????????? Strategy stra;
?????????????????????? public Context(Strategy stra) {
??????????????????????????????? ?this.stra = stra;
?????????????????????? }
?????????????????????? public void doMethod() {
???????????????????????????????? stra.method();
????????????????????? ?}
??????????????? }
?
?
?
?
?
??????????????? public class Test {?
??????????????? public static void main(String[] args) {
????????????????????????? Context ctx = new Context(new StrategyImplA());
????????????????????????? ctx.doMethod();
???????????????????????? ?ctx = new Context(new StrategyImp());?
????????????????????????? ctx.doMethod();
????????????????????????? ctx = new Context(new StrategyImplC()); ctx.doMethod();
?????????????? }?
?????????????? }??
???????????????3策略模式的优缺点
?????????????? 优点:
?????????????? 1.策略模式提供管理相关算法族的方法。
?????????????? 2.策略模式提供了可以替代继承的一种方法。
?????????????? 3.可以使程序避免使用多重选择语句。
?????????????? 缺点:
?????????????? 1.策略模式要求客户端必须知道所有的策略类。
?????????????? 2.策略模式产生了很多策略类。
???????????????例如策略模式只能处理客户端从几种方式中选择一种的情况,不能解决客户端同时选择一种以上的情况。这时策略模式就要和装饰模式共同应用。