2012-06-09 25 views
3

有人告诉我“的模式为构建接受孩子的可变参数,然后数据库对象的抽象容器暴露了一些孩子的检查功能,无需重复码”。必须有一个更好的实现代码:(

此提示到“count#of children”,“find by identifier”等事情。

为简单起见,下面的代码只有一个来自基本抽象DatabaseObject类型(即名称)的字段,但真正的代码有类似“标识符”和一些复杂的元数据查找噱头。

这个想法当然是有用的我只是看着我开始编码的东西让我想吐:如果我继续沿着这条道路前进,那将会是一个纠缠的科学怪人。任何方式使它成为体面的Java?任何设计模式参考? (Composite想到...)

前提:要共享的实际功能是有用的,并且实际上适用于任何可能的可嵌套类型(模式有表格,表格有列,有复合索引有子索引等),特别是标识符查找...

...但“必须有更好的方法”。我感觉到里面的声音说:“每当你写这样的代码时,都要打在脸上”。

帮助:)

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 ... 
    ... 
} 
+2

是的显然的情况下综合。例如。如果你想在组合中搜索某些东西,首先检查你是否满足谓词(然后返回这个或者某个东西),否则调用find来找所有的孩子。 – Voo

回答

0

复合想到速度非常快,但你也应该调查修饰模式。

找到明显的递归,但计数例如在叶子对象上非常有限,在所有类型的节点上都非常相似。

1

想想战略模式(http://en.wikipedia.org/wiki/Strategy_pattern)。原因:

  1. 解耦数据和数据操作。
  2. 您可以在运行时更改算法(“计数儿童数”,“通过标识符查找”)。

我想,它是这样的:

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; 
    } 
} 

然后,你可以使用依赖注入。

+0

我不太了解依赖注入......请问它在这里如何应用? – Robottinosino

0

与建议Composite模式从项目18(骨干实现):从有效的Java第二版不想接口到抽象类

  • 与方法定义的iterface(EntityCollection计数()查找()排序()删除()
  • 抽象类DatabaseContainerObject实现EntityCollection interface
  • Schema,延伸DatabaseContainerObject和实施EntityCollection接口CompositeIndex类。这里架构CompositeIndex是*元件* S在组合模式

优点是未来类可以扩展DatabaseContainerObject或实现EntityCollection

相关问题