您的位置:首页 > 其它

一点心得

2014-06-15 14:10 225 查看
项目中会遇到这样的逻辑处理:根据不同类型调用不同的方法,通常会用到if else等语句,感觉不太好;1,应该面向接口编程2,尽量避免使用if语句实例:原来代码,接口Iservice的实现类有 ServiceA ,ServiceB,ServiceC
public static void main(String[] args) {

String type = "C";
Iservice service = null;
if (type.equals("A")) {
service = new ServiceA();
}
if (type.equals("B")) {
service = new ServiceA();
}
if (type.equals("C")) {
service = new ServiceA();
}

service.printMsg();
}
上述代码,if语句会随着type取值的增加而增加,需要改动主业务代码
整改
import java.util.HashMap;
import java.util.Map;

public class Test {

private static Map<String, Iservice> m = new HashMap<String, Iservice>();

/**
* @param args
*/
public static void main(String[] args) {

cache();
String type = "B";
Iservice service = m.get(type);
service.printMsg();

}

private static void cache() {
// 緩存
if (m.isEmpty()) {
m.put("A", new ServiceA());
m.put("B", new ServiceB());
m.put("B", new ServiceB());
}
}

}
如上面代码:以后type类型有新增,只需修改 cache() 方法,增加对应实现即可,不用修改主业务代码

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: