对Child类使用ParentDecorator类

时间:2017-04-29 15:48:17

标签: java design-patterns

假设我有四个班级:

abstract class Parent {/*do stuff*/ }

class ChildA extends Parent {/*do more stuff*/}

class ChildB extends Parent {/*do more stuff differently*/}

class ParentDecorator extends Parent { 
  // do stuff
  doSomething() {
    //doing something
  }

}

如何在ChildA和ChildB对象中使用ParentDecorator方法doSomething()? 明显的答案是:

Parent child = new ParentDecorator(child);
((ParentDecorator) child).doSomething();

但我的情况是,我的所有对象都在以下列表中:

ArrayList<Parent> objects; 

我有像findObject(info)这样的方法,可以从列表中返回一个对象。

现在,假设我想从装饰器中为该列表中的特定对象调用doStuff。我可以这样做:

Parent child1 = findObject(info);
child1 = new ParentDecorator(child1);
((ParentDecorator) child1).doSomething();

但是有了这个,只有child1能够使用ParentDecorator功能,而findObject(info)将返回一个未更改的对象。 我试过这个:

( (ParentDecorator) findObject(info)).doSomething();

但它会抛出错误&#34; ChildA无法转换为ParentDecorator&#34;

我是否需要创建ChildADecorator和ChildBDecorator,这看起来有点多余?或者是否有一些似乎无法解决的解决方法?

1 个答案:

答案 0 :(得分:0)

我意识到我可以这样做:

Parent child1 = findObject(info);
child1 = new ParentDecorator(child1);
objects.remove(child1); //remove child1 from the object list
((ParentDecorator) child1).doSomething();
objects.add(child1);  //add it again

不是最优雅的解决方案,但它会做到