Java 对子类使用ParentDecorator类
假设我有四门课:Java 对子类使用ParentDecorator类,java,design-patterns,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 somethin
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
}
}
如何将ParentDecorator方法doSomething()用于ChildA和ChildB对象?
显而易见的答案是:
Parent child = new ParentDecorator(child);
((ParentDecorator) child).doSomething();
Parent child1 = findObject(info);
child1 = new ParentDecorator(child1);
((ParentDecorator) child1).doSomething();
但在我的情况下,我的所有对象都在如下列表中:
ArrayList<Parent> objects;
但是,只有child1能够使用ParentDecorator功能,findObject(info)将返回一个未更改的对象。
我试过这个:
( (ParentDecorator) findObject(info)).doSomething();
但它抛出了一个错误“ChildA不能转换为ParentDecorator”
我需要创建ChildADecorator和ChildBDecorator吗,这看起来有点多余?还是有一些我似乎无法解决的解决方法?我意识到我可以简单地做到这一点:
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
这不是最优雅的解决方案,但也可以