在程序中经常要使用==null来判定对象是否初始化,可以采用null object模式来简化这样的代码,从而提高健壮性。
/**
*
*/
/**
* @author lucy
*
*/
public abstract class AbstractProduct {
public String name;
public Integer price;
private static AbstractProduct nullProduct = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public static AbstractProduct getNullProduct() {
if (AbstractProduct.nullProduct == null) {
return new NullProduct();
}
return nullProduct;
}
}
public class NullProduct extends AbstractProduct {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public boolean isNull() {
return true;
}
}
public class Product extends AbstractProduct {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public boolean isNull() {
return false;
}
}