logo头像
Snippet 博客主题

避免过多if-else的几种方法

避免过多if-else的几种方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
String input = "three";

@Test
public void testElse() {
if ("one".equals(input)) {
System.out.println("one");
} else if ("two".equals(input)) {
System.out.println("two");
} else if ("three".equals(input)) {
System.out.println("three");
} else if ("four".equals(input)) {
System.out.println("four");
}
}

代码中一堆 if else
看起来 就 不舒服,不美观,又长

方法一 迭代模式

1
2
3
4
5
6
7
public interface INotification {

String getType();

void execute(String title ,String content);

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

public class WeChatNotification implements INotification {

static Pattern pWeixin = Pattern.compile("微信支付收款([\\d\\.]+)元");

@Override
public String getType() {
return Common.WECHAT_PACKAGE;
}

@Override
public void execute(String title ,String content) {
//TODO
}

}
}

初始化

1
2
3
4
5
6
7
8
9
private List<INotification> handlerList = new ArrayList<>();

handlerList.add(new AlipayNotification());
handlerList.add(new ECardPayNotification());
handlerList.add(new GuiZhouBankNotification());
handlerList.add(new SPayNotification());
handlerList.add(new WeChatNotification());
handlerList.add(new XingGuanJiaNotification());
handlerList.add(new ZhongYingBankNotification());

使用 迭代

1
2
3
4
5
6

for(INotification handler:handlerList){
if( handler.getType().contains(pkgName) ){
handler.execute(title,content);
}
}

这边也可以使用map
map 效率比list 高

方法一 工厂模式

1
2
3
4
5
6
7
public interface INotification {

String getType();

void execute(String title ,String content);

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class NotificationFactory {

public static INotification createMessage(String messageType) {

switch (messageType) {
case Common.e_card_PKG:
return new ECardPayNotification();

case Common.xiaomi_PKG:
case Common.guizhou_PKG:
return new GuiZhouBankNotification();

case Common.laijucai_PKG:
return new ZhongYingBankNotification();

case Common.SPay_PKG:
return new SPayNotification();

case Common.xingGuanjia_PKG:
return new XingGuanJiaNotification();

case Common.WECHAT_PACKAGE:
return new WeChatNotification();

case Common.ALIPAY_PACKAGE:
return new AlipayNotification();
default:
return null;
}
}

}

使用

1
2
INotification mNotification = NotificationFactory.createMessage(pkgName);
if (null != mNotification) mNotification.execute(title, content);
支付宝打赏 微信打赏

打赏