SearchCriteriaAnomalyFilter

SearchCriteriaAnomalyFilter

我在上个月的某个时候看到了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;
   }

    ...
}

最佳答案

public static final SearchCriteriaAnomalyFilter NULL_INSTANCE = new SearchCriteriaAnomalyFilter();
public static SearchCriteriaAnomalyFilter instanceOfNullObject(){
  return NULL_INSTANCE;
}


您的其余代码似乎还不错。

使用上述构造的原因是,无需进行延迟初始化:null对象将不会更改,也不需要任何特殊构造(如使用私有构造函数正确实现的那样)。

09-13 08:07