设计模式
来源:互联网 发布:网络性能测试包括什么 编辑:程序博客网 时间:2024/06/05 08:01
定义:策略模式定义了算法簇,分别封装起来,让它们之间可以互相替代,此模式让算法的变化独立于使用算法的客户。View CodeView CodeView CodeView CodeView CodeView Code
对象: 环境对象(Context):该类中实现了对抽象策略中定义的接口或者抽象类的引用。
抽象策略对象(Strategy):它可由接口或抽象类来实现。
具体策略对象(ConcreteStrategy):它封装了实现同不功能的不同算法或行为。
代码示例:
场景:我想要看不同的西游记片段,并且以后还可以添加或扩充其他的片段以供我观看。
抽象策略对象,提供不同算法和行为的入口。
package com.strategy;public interface SceneStrategy { void showScene();}
具体策略对象,实现抽象策略的方法,适应不同的算法和行为。
提供观看三打白骨精的场景。
package com.strategy;public class ThreeDozenBonesSceneStrategy implements SceneStrategy { @Override public void showScene() { System.out.println("西游记之三打白骨精"); }}
提供女儿国的场景。
package com.strategy;public class DaughterCountrySceneStrategy implements SceneStrategy { @Override public void showScene() { System.out.println("西游记之女儿国"); }}
提高真假美猴王的场景。
package com.strategy;public class TrueMonkeyKingSceneStrategy implements SceneStrategy { @Override public void showScene() { System.out.println("西游记之真假美猴王"); }}
环境对象,使用不同算法和行为的入口。
package com.strategy;public class WatchScene { private SceneStrategy sceneStrategy; public WatchScene(SceneStrategy sceneStrategy) { super(); this.sceneStrategy = sceneStrategy; } public void orderSceneShow(){ sceneStrategy.showScene(); }}
测试策略模式代码
package com.strategy;public class TestStrategy { public static void main(String[] args) { SceneStrategy daughterCountrySceneStrategy = new DaughterCountrySceneStrategy(); WatchScene watchScene = new WatchScene(daughterCountrySceneStrategy); watchScene.orderSceneShow(); SceneStrategy threeDozenBonesSceneStrategy = new ThreeDozenBonesSceneStrategy(); watchScene = new WatchScene(threeDozenBonesSceneStrategy); watchScene.orderSceneShow(); SceneStrategy trueMonkeyKingSceneStrategy = new TrueMonkeyKingSceneStrategy(); watchScene = new WatchScene(trueMonkeyKingSceneStrategy); watchScene.orderSceneShow(); }}
好处:
1、可以动态的改变对象的行为,以根据不同的需要或场景提供不同的算法和实现行为,但策略模式在每一个时刻只能使用一个具体的策略实现对象。
坏处:
1、客户端必须知道所有的策略类,并了解每个实现类的具体作用来自行决定使用哪一个策略类;
2、如果要实现的算法和行为比较多,那么策略模式将造成产生很多的策略类,如要看西游记81难的场景,就要实现81个实现类。
阅读全文
0 0
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式~~~~~~~~~~
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- JPush简单Java服务端案例实现
- 3-6 静态数据成员与静态成员函数
- Hessian服务端和客户端示例
- 使用cxf做webservice接口调用
- 关于云计算领域,你需要了解的52个术语
- 设计模式
- 第三章 DispatcherServlet详解 ——跟开涛学SpringMVC
- [LeetCode] Lowest Common Ancestor of a Binary Tree 二叉树的最小共同父节点
- 设计模式
- 设计模式
- ArrayList源码浅析(jdk1.8)
- LinkedList源码浅析(jdk1.8)
- nodejs常用命令
- JSP简介