作为java程序员,最讨厌的莫过于解决无穷无尽的nullpointexception.其实利用null object模式优雅的解决这个问题:
public interface Employee{
public void pay();
public boolean isTimeToPay(Date payDate);
public static final Employee NULL = new Employee(){
public boolean isTimeToPay(Date payDate){
return false;
}
public void pay(){
}
};
}
public class DB{
private static Map<String,Employee> EmployMap= new HashMap<String,Employee>();
static {
EmployMap.put("jeff", new EmployImp());
}
public static Employee getEmployee(String name){
Employee e = EmployMap.get(name);
if(e == null)
return Employee.NULL;
return e;
}
}
public class EmployImp implements Employee {
@Override
public void pay() {
DebugLog.log("payed");
}
@Override
public boolean isTimeToPay(Date payDate) {
return true;
}
}
public class Test {
public static void main(String[] args) {
Employee e = DB.getEmployee("xxxx");
Date today =new Date();
if(e.isTimeToPay(today))
e.pay();
}
public void testPay()
{
Employee e = DB.getEmployee("Bob");
Date today =new Date();
if(e != null && e.isTimeToPay(today))
e.pay();
}
}
Employ 从db里面拿出相应的employ,按照以前的代码在使用具体方法之前
需要加上相应的判断,各位看官完全可以使用null object pattern优雅的解决
这个问题