赞
踩
替换掉 多层 if else 嵌套方法:
模拟场景:不同的渠道类型分别使用不同的逻辑处理。
渠道类型:储蓄卡、信用卡、公众号
一般实现:
public static final String depositCard = "depositCard"; public static final String creditCard = "creditCard "; public static final String OfficialAccounts = "OfficialAccounts"; public void auto(String channelType) { if (!StringUtils.isEmpty(channelType)) { if (depositCard.equals(channelType)) { //TODO } else if (creditCard .equals(channelType)) { //TODO } else if (OfficialAccounts.equals(channelType)) { //TODO } else { //TODO } } }
接口分层:
接口分层,就是把接口分为对内接口和对外接口,非空的判断放在外层接口处理,对内接口传入的变量由外部接口保证不为空,从二减少空值判断。
public static final String depositCard = "depositCard"; public static final String creditCard = "creditCard "; public static final String OfficialAccounts = "OfficialAccounts"; public void auto(String channelType) { if (!StringUtils.isEmpty(channelType)) { autoImpl(channelType); } } private void autoImpl(String channelType) { if (depositCard.equals(channelType)) { //TODO } else if (creditCard .equals(channelType)) { //TODO } else if (OfficialAccounts.equals(channelType)) { //TODO } else { //TODO } }
多态实现:
public abstract class Channel { public String type; public Channel(String type) { this.type = type; } public abstract void auto(); } public class DepositCardChannel extends Channel { public DepositCardChannel(String type) { super(type); } @Override public void auto() { System.out.println("This is DepositCardChannel"); } } public class CreditCardChannel extends Channel { public CreditCardChannel(String type) { super(type); } @Override public void auto() { System.out.println("This is CreditCardChannel"); } } public void auto(Policy policy) { if (policy != null) { autoImpl(policy); } } public void autoImpl(Policy policy) { policy.auto(); }
好了,一个 if else 也没有了,如果有 新增类型,只需要增加一个 类继承 Channel,
使用Map替代分支语句:
private static Map<String, Class<? extends Policy>> map = new HashMap<>(); public static final String OPEN_POLICY = "OpenPolicy"; public static final String SUB_POLICY = "SubPolicy"; static { map.put(OPEN_POLICY, OpenPolicy.class); map.put(SUB_POLICY, SubPolicy.class); } public void auto(String policyType) { try { Class<? extends Policy> clazz = map.get(policyType); clazz.newInstance().auto(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。