NULL OBJECT看着这个名字应该有一个笼统的印象了。翻译成中文就是“空对象”。提供一个对象给指定的类型,用以代替这个对象为空的情况。 Null Object提供了“什么也不做”的行为,隐藏来自它的合作者的细节
那在FrameWork中有这样的设计模式吗?答案是肯定的,比如:String.Empty,Decimal.Zero等 以下是简单例子:
public interface Employee{
public void pay();
public boolean isTimeToPay(DateTime payDate);
public static final Employee NULL = new Employee(){
public boolean isTimeToPay(DateTime payDate){
return false;
}
public void pay(){
}
};
}
public class DB{
private static Map<String,Employee> EmployMap= new HashMap<String,Employee>();
static {
EmployMap.put("Wilson", 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 {
public Override void pay() {
DebugLog.log("payed");
}
public Override 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();
}
}
public void pay();
public boolean isTimeToPay(DateTime payDate);
public static final Employee NULL = new Employee(){
public boolean isTimeToPay(DateTime payDate){
return false;
}
public void pay(){
}
};
}
public class DB{
private static Map<String,Employee> EmployMap= new HashMap<String,Employee>();
static {
EmployMap.put("Wilson", 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 {
public Override void pay() {
DebugLog.log("payed");
}
public Override 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();
}
}