类图
代码
Stragegy
1 | interface Vehicle{ |
ConreteStrategy1
1 | class Car implements Vehicle{ |
ConreteStrategy2
1 | class Bicycle implements Vehicle{ |
Context
1 | class Person{ |
测试类
1 | public class Main { |
总结
优点
- 策略模式提供了一个算法或者行为族的定义
- 使用策略模式可以一定程度避免if-else语句
缺点
- 客户端必须知道具体算法的区别,才用选择对应的策略进行使用