OO - inheritance vs. decoration problem
Posted
by Karel J
on Stack Overflow
See other posts from Stack Overflow
or by Karel J
Published on 2010-05-26T18:29:23Z
Indexed on
2010/05/26
18:31 UTC
Read the original article
Hit count: 286
oop
Hi all,
I have an OOP-related question. I have an interface, say:
class MyInterface {
public int getValue();
}
In my project, this interface is implemented by 7 implementations:
class MyImplementation1 implements MyInterface { ... }
...
class MyImplementation7 implements MyInterface { ... }
These implementations are used by several different modules. For some modules, the behaviour of the MyInterface must be adjusted slightly. Let's that it must return the value of the implementator + 1 (for the sake of example). I solved this by creating a little decorator:
class MyDifferentInterface implements MyInterface {
private MyInterface i;
public MyDifferentInterface(MyInterface i) {
this.i = i;
}
public int getValue() {
return i.getValue() + 1;
}
}
This does the job.
Here is my problem: one of the modules doesn't accept an MyInterface parameter, but MyImplementation4 directly. The reason for this is that this module needs specific behaviour of MyImplementation4, which are not covered by the interface MyInterface on itself. But, and here comes the difficulty, this module must also work on the modified version of MyImplementation4. That is, getValue() must return +1;
What is the best way to solve this? I fail to come up with a solution which does not include lots of code duplicates.
Please note that although the example above is pretty small and simple, the interface and the decorator is quite large and complicated.
Thanks a lot all.
© Stack Overflow or respective owner