簡體   English   中英

用模式重構

[英]Refactoring with patterns

我沒有關於模式和應用程序體系結構的大量實踐。 簡而言之,我必須找到對象特征的某些屬性。 一些代碼可以更好地描述任務:

IAttribute {
  IAttribute analyze(IFunction func);
}

//up to 10 different attributes
ArgumentsAttribute implements Attribute {
  Map<String, ArgType> args = new HashMap<>();
  IAttribute analyze(IFunction func) {
    for (Argument arg : func.getArgs()) {
      args.put(arg.getName(), arg.getType());
    }

    if (!args.isEmpty()) return this;
    return null;
  }
}

ReturnAttribute implements Attribute {
  IAttribute analyze(IFunction func) {
    if (func.hasReturn) return this;
    return null;
  }
}


AttributeAnalyzer {
  List<Attributes> analyzeAttributes(IFunction func) {


    List<IAttribute> attributes = new ArrayList<IAttribute>();
    attributes.add(new ArgumentAttribute());
    attributes.add(new ReturnAttribute());
    ...

    for (IAttribute attr : attributes) {
        attr = attr.analyze(func);
        if (null == attr) attributes.remove(attr);
    }

    return attributes;
  }
}

但是,此實現似乎有些奇怪。 我不喜歡Attribute是某種持有人的事實,但是它必須實現方法來查找自身。 我認為,最佳實踐是重載靜態方法的機會,但顯然不可能。 這樣,我們就可以將持有人從分析邏輯中分離出來,而無需添加新的抽象(也許我是不對的)。

IAttribute {
  static IAttribute analyze();
}

ConcreteAttribute1 {
  int x = 0;
  static IAttribute analyze() {
    ...
    if (x != 0) return new ConcreteAttribute1();
    return null;
  }
}

ConcreteAttribute2 {
  String s = "";
  static IAttribute analyze() {
  ...
  if (!s.equals("")) return new ConcreteAttribute2();
  return null;
  }
}


AttributeAnalyzer {
  List<Attributes> analyzeAttributes() {


    List<IAttribute> attributes = new ArrayList<IAttribute>();
    attributes.add(ConcreteAttribute1.analyze());
    attributes.add(ConcreteAttribute2.analyze());
    ...

    for (IAttribute attr : attributes) {
        if (null == attr) attributes.remove(attr);
    }

    return attributes;
 }

}

另外,我必須過濾損壞的屬性。 那么,有沒有什么方法可以使代碼看起來更好呢?

如果您對每個具體屬性都具有獨特的analyze功能,幾乎沒有重疊,那么您的初始代碼示例可能就不是那么糟糕。 但是,我隨后將方法的簽名更改為boolean analyze()

如果分析屬性的方式有更多重疊,則可以考慮在AttributeAnalyzer類(或專用類)中使用單個方法boolean analyze(IAttribute) )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM