Lets say I have four classes:
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
}
}
How can i use ParentDecorator method doSomething() with ChildA and ChildB objects? The obvious answer would be something like:
Parent child = new ParentDecorator(child);
((ParentDecorator) child).doSomething();
but my case, all my objects are in a lists like:
ArrayList<Parent> objects;
and i have methods like findObject(info)
which returns an object from the list.
Now, lets say i want to call doStuff from the decorator for a specific object from that list. I can do something like:
Parent child1 = findObject(info);
child1 = new ParentDecorator(child1);
((ParentDecorator) child1).doSomething();
but with this, only child1 will be able to use ParentDecorator functionality, and findObject(info) will return an unchanged object. I tried this:
( (ParentDecorator) findObject(info)).doSomething();
but it throws an error "ChildA cannot be cast to ParentDecorator"
Do i need to creat ChildADecorator and ChildBDecorator, which seems a bit redundant? Or is there some workaround i cant seem to figure out?
Aucun commentaire:
Enregistrer un commentaire