wutzebaer
wutzebaer

Reputation: 14863

Override function for multiple Inheritance hierarchies

I have two class hierarchies

A -> X -> Z
B -> Y -> Z

X, Y and Z are Library Functions and so they are unchangeable.

Z has a function myfunc()

Now i want to add some code to myfunc() when it is called on a A or B instance.

How can i change my Inheritance hierarchy that i've to implement the additional code only once? Is there any pattern?

Upvotes: 1

Views: 52

Answers (2)

David Tanzer
David Tanzer

Reputation: 2742

Use delegation to implement the new functionality. This not only solves your problem, but also adds some seams for testing.

class A extends X {
    private ZDelegate delegate;

    public A(ZDelegate delegate) {
        this.delegate = delegate;
    }

    public R myFunc(P param) {
        return delegate.myFunc(this, param);
    }
}

public class ZDelegate {
    public R myFunc(Z z, P param) {
        //your code
        z.myFunc(param);
        //your code
        //return something...
    }
}

You have a new class (ZDelegate) with a clear, single responsibility: Enhancing myFunc.

The seams for testing are: You can test your new myFunc independently of everything else. And you can test your A and B objects independently from ZDelegate. You can do both either with fakes or mock objects.

Your A and B objects are still very closely coupled to X, Y and Z though...

Upvotes: 3

Norwæ
Norwæ

Reputation: 1575

You should probably factor out your new implementation of myfunc() to a delegate object, and override myfunc to point to the delegate. Here is an example.

class MyFuncDelegate() {
    static void myFunc() {
        // your code
    }
}

class A {
    void myFunc() {
        super.myFunc();
        Delegate.myFunc();
    }
}

B can then use the same pattern. Not very object-oriented, avoids repeating yourself.

Upvotes: 3

Related Questions