我在上个月的某个时候看到Null Object模式的实现看起来像是一个类型上的Singleton字段。我不记得这个方法了。我正在研究模式并意识到将它们实现到位。
从我的想法,我认为它会如下,但我可以对此进行审查吗?
public final class SearchCriteriaAnomalyFilter {
public static final SearchCriteriaAnomalyFilter NULL_INSTANCE;
private final T2AnomalyStatus status;
private final T2AnomalyType type;
private final boolean limitMaxOneAnomaly;
public SearchCriteriaAnomalyFilter(T2AnomalyStatus status, T2AnomalyType type,
boolean limitMaxOneAnomaly){
this.status = status;
this.type = type;
this.limitMaxOneAnomaly = Boolean.valueOf(limitMaxOneAnomaly);
}
private SearchCriteriaAnomalyFilter(){}
public static SearchCriteriaAnomalyFilter instanceOfNullObject(){
if (NULL_INSTANCE == null) {
NULL_INSTANCE = new SearchCriteriaAnomalyFilter();
}
return NULL_INSTANCE;
}
...
}
答案 0 :(得分:1)
public static final SearchCriteriaAnomalyFilter NULL_INSTANCE = new SearchCriteriaAnomalyFilter();
public static SearchCriteriaAnomalyFilter instanceOfNullObject(){
return NULL_INSTANCE;
}
你的其余代码似乎很好。
使用上述构造的原因是不需要延迟初始化:null-object不会改变,也不需要任何特殊构造(正如你使用私有构造函数正确实现的那样)。