设计模式-21-策略模式
个人github地址:HibisciDai
设计模式系列项目源码:HibisciDai/DesignPattern-LearningNotes-HibisciDai
processon在线UML类图:processon
[TOC]
设计模式-21-策略模式 策略模式(Strategy Pattern) 意图 定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。
define a finallu or a lgorithed,encapsulate each owe,and make them interchangeable,strategy lets the algorithm vary independently from cilents that use it.
主要解决 在有多种算法相似的情况下,使用 if…else 所带来的复杂和难以维护。
何时使用 一个系统有许多许多类,而区分它们的只是他们直接的行为。
关键代码 实现同一个接口。
如何解决 将这些算法封装成一个一个的类,任意地替换。
应用实例
诸葛亮的锦囊妙计,每一个锦囊就是一个策略。
旅行的出游方式,选择骑自行车、坐汽车,每一种旅行方式都是一个策略。
JAVA AWT 中的 LayoutManager。
优点
算法可以自由切换。
避免使用多重条件判断。
扩展性良好。
缺点
使用场景
如果在一个系统里面有许多类,它们之间的区别仅在于它们的行为,那么使用策略模式可以动态地让一个对象在许多行为中选择一种行为。
一个系统需要动态地在几种算法中选择一种。
如果一个对象有很多的行为,如果不用恰当的模式,这些行为就只好使用多重的条件选择语句来实现。
注意事项 如果一个系统的策略多于四个,就需要考虑使用混合模式,解决策略类膨胀的问题。
案例1 旅行有选择走路的方式和路上吃什么干粮有很多选择。
类图
代码 pattern21.strategy.demo1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 public interface ITravelStrategy { public void buyTicket () ; public void otherOper () ; } public class Train implements ITravelStrategy { @Override public void buyTicket () { System.out.println("一张火车票" ); } @Override public void otherOper () { System.out.println("吃的火车餐" ); } } public class AirPlan implements ITravelStrategy { @Override public void buyTicket () { System.out.println("一张飞机票" ); } @Override public void otherOper () { System.out.println("吃的飞机餐" ); } } public class Bicycle implements ITravelStrategy { @Override public void buyTicket () { System.out.println("一辆单车" ); } @Override public void otherOper () { System.out.println("自备食餐" ); } } public class Travel { private ITravelStrategy st; public void setSt (ITravelStrategy st) { this .st = st; } public void go () { st.buyTicket(); st.otherOper(); } }
测试输出 1 2 3 4 5 6 7 8 9 10 11 public class Main { public static void main (String[] args) { Travel t = new Travel (); t.setSt(new AirPlan ()); t.go(); t.setSt(new Train ()); t.go(); t.setSt(new Bicycle ()); t.go(); } }
1 2 3 4 5 6 一张飞机票 吃的飞机餐 一张火车票 吃的火车餐 一辆单车 自备食餐