【转载】Java策略消除if else
策略(Strategy)模式:又名Policy,它的用意是定义一组算法,把它们一个个封装起来,并且使他们可以相互替换。策略模式可以独立于使用他们的客户端而变化。GOF策略模式静态结构类图如下:
通过上图可以看出策略模式有以下角色构成:
1、抽象策略(Strategy)角色:抽象策略角色由抽象类或接口来承担,它给出具体策略角色需要实现的接口;
2、具体策略(ConcreteStrategy)角色:实现封装了具体的算法或行为;
3、场景(Context)角色:持有抽象策略类的引用。
策略模式重点是封装不同的算法和行为,不同的场景下可以相互替换。策略模式是开闭原则的体现,开闭原则讲的是一个软件实体应该对扩展开放对修改关闭。策略模式在新的策略增加时,不会影响其他类的修改,增加了扩展性,也就是对扩展是开放的;对于场景来说,只依赖于抽象,而不依赖于具体实现,所以对修改是关闭的。策略模式的认识可以借助《java与模式》一书中写到诸葛亮的锦囊妙计来学习,在不同的场景下赵云打开不同的锦囊,便化险为夷,锦囊便是抽象策略,具体的锦囊里面的计策便是具体的策略角色,场景就是赵云,变化的处境
选择具体策略的条件。
策略模式在程序设计中也很常用,在板桥(banq)的博客里有篇文章叫 “你还在用if else吗?”
“http://www.jdon.com/artichect/ifelse.htm”讲的很好,策略模式不但是继承的代替方案而且能很好地解决if else问题,下面举个实例来说明,怎么使用策略模式。
需求如下:
某支付系统接入以下几种商户进行充值:易宝网易,快线网银,19pay手机支付,支付宝支付,骏网一卡通,由于每家充值系统的结算比例不一样,而且同一家商户的不同充值方式也有所不同,具体系统情况比较复杂,像支付宝既有支付宝账号支付和支付宝网银支付等这些暂时不考虑,为了讲述策略模式这里简单描述,假如分为四种,手机支付,网银支付,商户账号支付和点卡支付。因为没个支付结算比例不同,所以对手续费低的做一些优惠活动,尽可能让用户使用手续费低的支付方式来充值,这样降低渠道费用,增加收入,具体优惠政策如下:
①网银充值,8.5折;
②商户充值,9折;
③手机充值,没有优惠;
④点卡充值,收取1%的渠道费;
对于一个新手的代码如下:
package strategy; public class Example { /**
*
*作者:alaric
*时间:2013-8-5上午11:00:06
*描述:计算用户所付金额
*/
public Double calRecharge(Double charge ,RechargeTypeEnum type ){ if(type.equals(RechargeTypeEnum.E_BANK)){
return charge*0.85;
}else if(type.equals(RechargeTypeEnum.BUSI_ACCOUNTS)){
return charge*0.90;
}else if(type.equals(RechargeTypeEnum.MOBILE)){
return charge;
}else if(type.equals(RechargeTypeEnum.CARD_RECHARGE)){
return charge+charge*0.01;
}else{
return null;
} } }
package strategy; public enum RechargeTypeEnum { E_BANK(1, "网银"), BUSI_ACCOUNTS(2, "商户账号"), MOBILE(3,"手机卡充值"), CARD_RECHARGE(4,"充值卡")
; /**
* 状态值
*/
private int value; /**
* 类型描述
*/
private String description; private RechargeTypeEnum(int value, String description) {
this.value = value;
this.description = description;
} public int value() {
return value;
}
public String description() {
return description;
} public static RechargeTypeEnum valueOf(int value) {
for(RechargeTypeEnum type : RechargeTypeEnum.values()) {
if(type.value() == value) {
return type;
}
}
return null;
}
}
可以看出上面四种不同的计算方式在一个方法内部,不利于扩展和维护,当然也不符合面向对象设计原则。对以上的代码利用策略模式进行修改,类图如下:
实例代码如下:
- package strategy.strategy;
- import strategy.RechargeTypeEnum;
- /**
- *
- *作者:alaric
- *时间:2013-8-5上午11:03:17
- *描述:策略抽象类
- */
- public interface Strategy {
- /**
- *
- *作者:alaric
- *时间:2013-8-5上午11:05:11
- *描述:策略行为方法
- */
- public Double calRecharge(Double charge ,RechargeTypeEnum type );
- }
- package strategy.strategy;
- import strategy.RechargeTypeEnum;
- /**
- *
- *作者:alaric
- *时间:2013-8-5上午11:14:23
- *描述:网银充值
- */
- public class EBankStrategy implements Strategy{
- @Override
- public Double calRecharge(Double charge, RechargeTypeEnum type) {
- return charge*0.85;
- }
- }
- package strategy.strategy;
- import strategy.RechargeTypeEnum;
- /**
- *
- *作者:alaric
- *时间:2013-8-5上午11:14:08
- *描述:商户账号充值
- */
- public class BusiAcctStrategy implements Strategy{
- @Override
- public Double calRecharge(Double charge, RechargeTypeEnum type) {
- // TODO Auto-generated method stub
- return charge*0.90;
- }
- }
- package strategy.strategy;
- import strategy.RechargeTypeEnum;
- /**
- *
- *作者:alaric
- *时间:2013-8-5上午11:14:43
- *描述:手机充值
- */
- public class MobileStrategy implements Strategy {
- @Override
- public Double calRecharge(Double charge, RechargeTypeEnum type) {
- // TODO Auto-generated method stub
- return charge;
- }
- }
- package strategy.strategy;
- import strategy.RechargeTypeEnum;
- /**
- *
- *作者:alaric
- *时间:2013-8-5上午11:13:46
- *描述:充值卡充值
- */
- public class CardStrategy implements Strategy{
- @Override
- public Double calRecharge(Double charge, RechargeTypeEnum type) {
- return charge+charge*0.01;
- }
- }
- package strategy.strategy;
- import strategy.RechargeTypeEnum;
- /**
- *
- *作者:alaric
- *时间:2013-8-5上午11:03:38
- *描述:场景类
- */
- public class Context {
- private Strategy strategy;
- public Double calRecharge(Double charge, Integer type) {
- strategy = StrategyFactory.getInstance().creator(type);
- return strategy.calRecharge(charge, RechargeTypeEnum.valueOf(type));
- }
- public Strategy getStrategy() {
- return strategy;
- }
- public void setStrategy(Strategy strategy) {
- this.strategy = strategy;
- }
- }
- package strategy.strategy;
- import java.util.HashMap;
- import java.util.Map;
- import strategy.RechargeTypeEnum;
- /**
- *
- *作者:alaric
- *时间:2013-8-5上午11:31:12
- *描述:策略工厂 使用单例模式
- */
- public class StrategyFactory {
- private static StrategyFactory factory = new StrategyFactory();
- private StrategyFactory(){
- }
- private static Map<Integer ,Strategy> strategyMap = new HashMap<>();
- static{
- strategyMap.put(RechargeTypeEnum.E_BANK.value(), new EBankStrategy());
- strategyMap.put(RechargeTypeEnum.BUSI_ACCOUNTS.value(), new BusiAcctStrategy());
- strategyMap.put(RechargeTypeEnum.MOBILE.value(), new MobileStrategy());
- strategyMap.put(RechargeTypeEnum.CARD_RECHARGE.value(), new CardStrategy());
- }
- public Strategy creator(Integer type){
- return strategyMap.get(type);
- }
- public static StrategyFactory getInstance(){
- return factory;
- }
- }
- package strategy.strategy;
- import strategy.RechargeTypeEnum;
- public class Client {
- /**
- * 作者:alaric 时间:2013-8-5上午11:33:52 描述:
- */
- public static void main(String[] args) {
- Context context = new Context();
- // 网银充值100 需要付多少
- Double money = context.calRecharge(100D,
- RechargeTypeEnum.E_BANK.value());
- System.out.println(money);
- // 商户账户充值100 需要付多少
- Double money2 = context.calRecharge(100D,
- RechargeTypeEnum.BUSI_ACCOUNTS.value());
- System.out.println(money2);
- // 手机充值100 需要付多少
- Double money3 = context.calRecharge(100D,
- RechargeTypeEnum.MOBILE.value());
- System.out.println(money3);
- // 充值卡充值100 需要付多少
- Double money4 = context.calRecharge(100D,
- RechargeTypeEnum.CARD_RECHARGE.value());
- System.out.println(money4);
- }
- }
运行结果:
85.0
90.0
100.0
101.0
【转载】Java策略消除if else的更多相关文章
- 【转】Java策略消除if else
策略(Strategy)模式:又名Policy,它的用意是定义一组算法,把它们一个个封装起来,并且使他们可以相互替换.策略模式可以独立于使用他们的客户端而变化.GOF策略模式静态结构类图如下: 通过上 ...
- [转载]Java中继承、装饰者模式和代理模式的区别
[转载]Java中继承.装饰者模式和代理模式的区别 这是我在学Java Web时穿插学习Java设计模式的笔记 我就不转载原文了,直接指路好了: 装饰者模式和继承的区别: https://blog.c ...
- [转载]Java序列化与反序列化
[转载]Java序列化与反序列化 来源: https://www.cnblogs.com/anitinaj/p/9253921.html 序列化和反序列化作为Java里一个较为基础的知识点,那你能说一 ...
- [转载]java中import作用详解
[转载]java中import作用详解 来源: https://blog.csdn.net/qq_25665807/article/details/74747868 这篇博客讲的真的很清楚,这个作者很 ...
- [转载]Java中异常的捕获顺序(多个catch)
http://blog.sina.com.cn/s/blog_6b022bc60101cdbv.html [转载]Java中异常的捕获顺序(多个catch) (2012-11-05 09:47:28) ...
- [转载] java垃圾回收机制
转载自http://blog.csdn.net/randyjiawenjie/article/details/7551228 http://www.daniel-journey.com/archive ...
- Java策略模式以及来自lambda的优化
前言 设计模式是软件工程中一些问题的统一解决方案的模型,它的出现是为了解决一些普遍存在的,却不能被语言特性直接解决的问题,随着软件工程的发展,设计模式也会不断的进行更新,本文介绍的是经典设计模式 ...
- [转载]java开发中的23种设计模式
原文链接:http://blog.csdn.net/zhangerqing 设计模式(Design Patterns) ——可复用面向对象软件的基础 设计模式(Design pattern)是一套被反 ...
- java 策略设计模式
在软件开发中也常常遇到类似的情况,实现某一个功能有多种算法或者策略,我们可以根据环境或者条件的不同选择不同的算法或者策略来完成该功能.如查找.排序等,一种常用的方法是硬编码(Hard Coding)在 ...
随机推荐
- GridView分页功能的实现
当GridView中显示的记录很多的时候,可以通过GridView的分页功能来分页显示这些记录.如果GridView是直接绑定数据库,则很简单:将"启动分页"打勾即可. 如果是用代 ...
- Changing the Auto-Logout Timeout in SSH
SSH: We can set a timeout interval for ssh client who are idle or in inactive state. As soon as the ...
- file_get_contents post数据
//默认模拟的header头 private function _defaultHeader() { $header = "User-Agent:Mozilla/5.0 (Windows; ...
- 老男孩python第六期
01 python s6 day7 上节回顾02 python s6 day7 SNMP使用03 python s6 day7 大型监控架构讲解04 python s6 day7 Redis使用05 ...
- CCNP路由实验(2) -- OSPF
OSPF作为一种内部网关协议(IGP),用于在同一个AS中的路由器之间交换路由信息.OSPF的特性如下:1.可适应大规模网络2.收敛速度快3.无路由环路4.支持VLSM和CIDR5.支持等价路由6.支 ...
- [cpp]伯乐在线编程挑战第 0 期 – 呼叫转移系统
题目: 描述 呼叫转移服务是一个把呼叫号码A转移到号码B的服务.举个例子:当你正在度假时,这样的系统非常有帮助.A君度假去了,那么,A君的工作电话可以通 过呼叫转移至B君.更进一步讲,当B君也正好在度 ...
- [置顶] 【cocos2d-x入门实战】微信飞机大战之二:别急,先处理好CCScene和CCLayer的关系
转载请表明地址:http://blog.csdn.net/jackystudio/article/details/11713197 在整个游戏开始之前,我们先看一下HelloWorld示例中CCSce ...
- JAVA学习第一课(初识JAVA)
PS:退ACM集训队了,自己也疯玩了两天,后天就开学了,就正式大二了,该收收心好好学习啦 ...
- C++ STL中map存储方式——SAP电面(4)
map存储方式 一般是平衡二叉树 红黑树
- 操作百度API
string json = ""; try { //虽然两者都是异步请求事件,但是WebClient是基于事件的异步,而HttpWebRequst是基于代理的异步编程 WebCli ...