繁体   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