Reputation: 16143
Lets say, we have a given external library with a tree data structure. Example: Superclass S
with Subclass B1
to B5
. The subclasses may have subclasses, too.
Now I want to add an additional method for this datastructure. Normally, one would implement it by using polymorphism: Each subcluss implements the specific method.
But because we deal with an external library, we can't change the original classes. There are two alternative solutions coming in my mind:
instanceof
Which approach is the common case ? Or, is there a better alternative solution ?
Upvotes: 2
Views: 156
Reputation: 136062
Decorator pattern might come in handy
class S2 extends S {
S s;
S2(S s) {
this.s = s;
}
// delegate method calls to wrapped B1-B5 instance
@Override
void oldMethod1() {
s.oldMethod1();
}
...
// add new methods
void newMetod1() {
...
}
}
then use it as
new S2(new B1());
or on an existing instance of B1
new S2(b1);
Upvotes: 1
Reputation: 84
Decorator Design Pattern may help. You can have a decorator class that extends from Class S
. And it wraps an S
also. You can implement your method in the decorator.
Upvotes: 3
Reputation: 18296
The Visitor Design Pattern gives you the ability to "add" new operations to existing data structures.
Upvotes: 1