设计模式-多重if的应用
文章目录
策略模式改进多重if结构
多重if代码示例
/**
* 支付方式
*
* @author admin
*/
enum PayEnum {
/**
* 支付宝
*/
ALI_PAY("ali", "支付宝支付"),
/**
* 微信
*/
WECHAT_PAY("wechat", "微信支付"),
/**
* 银联
*/
UNION_PAY("union", "银联支付");
private String channel;
private String desc;
PayEnum(String channel, String desc) {
this.channel = channel;
this.desc = desc;
}
public static PayEnum getPayEnumByChannel(String channel) {
PayEnum[] enums = PayEnum.values();
for (PayEnum payEnum : enums) {
if (payEnum.getChannel().equals(channel)) {
return payEnum;
}
}
return null;
}
public String getChannel() {
return channel;
}
public String getDesc() {
return desc;
}
}
/**
* @author admin
*/
public interface PayService {
/**
* 付款
* @param channel
* @param amount
* @return
* @throws Exception
*/
String pay(String channel, String amount) throws Exception;
}
/**
* @author admin
*/
class PayServiceImpl implements PayService {
@Override
public String pay(String channel, String amount) throws Exception {
String payMsg = "您使用 %s ,消费了 %s 元";
// 方式一
if (PayEnum.ALI_PAY.getChannel().equals(channel)) {
// 业务代码...
return String.format(payMsg, PayEnum.ALI_PAY.getDesc(), amount);
} else if (PayEnum.WECHAT_PAY.getChannel().equals(channel)) {
// 业务代码...
return String