John Threepwood
John Threepwood

Reputation: 16143

How to add a new method to a given data structure in a good way?

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:

  1. Create a new class with a method which checks case for case by using instanceof
  2. Create subclasses for each class an implement the methods there.

Which approach is the common case ? Or, is there a better alternative solution ?

Upvotes: 2

Views: 156

Answers (3)

Evgeniy Dorofeev
Evgeniy Dorofeev

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

LazyChild
LazyChild

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

Itay Karo
Itay Karo

Reputation: 18296

The Visitor Design Pattern gives you the ability to "add" new operations to existing data structures.

Upvotes: 1

Related Questions