Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 对子类使用ParentDecorator类_Java_Design Patterns - Fatal编程技术网

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
这不是最优雅的解决方案,但也可以