我被告知“为数据库对象建模一个抽象容器,该容器构造接受子项的可变参数,然后在没有代码重复的情况下公开一些子项检查功能”。
这暗示了诸如“计算 child 的数量”、“通过标识符查找”等事情。
为简单起见,下面的代码只有一个来自基本抽象 DatabaseObject 类型的字段(即名称),但真正的代码有诸如“标识符”之类的东西和一些复杂的元数据查找噱头。
这个想法当然很有用,但只要看看我开始编写的代码就让我想吐:如果我继续沿着这条路走下去,这将是一个科学怪人的纠缠。有什么办法可以把它变成像样的 Java 吗?有什么设计模式可以引用吗? (想到复合...)
前提:要共享的实际功能是有用的,并且确实适用于任何潜在的可嵌套类型(模式有表,表有列,复合索引有子索引等),尤其是标识符查找。 ..
...但是“必须有更好的方法”。我感觉到我内心的那个声音在说“每当你这样写代码的时候,就打自己的脸”。
帮助:)
public abstract class DatabaseContainerObject<ChildType extends DatabaseObject>
extends DatabaseObject {
protected List<ChildType> children;
public DatabaseContainerObject(String name, ChildType... children) {
super(name);
this.children = new ArrayList<ChildType>(children.length);
this.children.addAll(Arrays.asList(children));
}
protected List<ChildType> getChildren() {
return Collections.unmodifiableList(children);
}
... count ...
... find ...
... sort ...
... remove ...
...
}
最佳答案
考虑策略模式 (http://en.wikipedia.org/wiki/Strategy_pattern)。原因:
- 解耦数据和数据操作。
- 您可以在运行时更改算法(“计算 child 的数量”、“按标识符查找”)。
我猜是这样的:
public abstract class DatabaseContainerObject<ChildType extends DatabaseObject>
extends DatabaseObject {
protected List<ChildType> children;
private DataOperator dataOperator;
public Object find(){
return dataOperator.find(children);
}
}
public interface DataOperator{
public <ChildType extends DatabaseObject> find(List<ChildType> childList);
}
public Class GeneralDataOperator extends DataOperator{
public <ChildType> find(List<ChildType> childList){
//implements find;
}
}
然后,您可以使用依赖注入(inject)。
关于java - 必须有更好的方法来编码这个 :(,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10961737/