I have an library with interface which contains substential amount of method declarations:
interface ILibInterface
{
public method1();
public method2();
public method3();
// etc.
}
and class that implement this iterface:
class LibClass : ILibInterface
{
public method1(){ /* ... */}
public method2(){ /* ... */}
public method3(){ /* ... */}
// etc.
}
Now, I wrote a couple of decorators for the LibClass, an example:
class MyLibClassDecorator1
// : ILibInterface <- this is what I want
{
LibClass backingObject;
public MyLibClassDecorator1(LibClass obj)
{
this.backingObject = obj;
}
public LibClass GetBackingObject()
{
return this.backingObject;
}
}
What I want to achieve is to be able to use that decorators as ILibInterface objects, which means that they all have to implement it. But this is a lot of code repetition like:
public method1() { return this.backingObject.method1(); }
public method2() { return this.backingObject.method2(); }
// etc.
Is there a smart way to implement all methods in the ILibInterface, while sticking to the DRY rule?
Note 1: The library is mine, so I can alter both ILibInterface and LibClass, but I'd rather not, as I am aiming for an answer that would let me to do the same with 3rd party libraries.
Note 2: I appreciate answer in either C#/Java/PHP.
First of all most of good design principles are strongly related to the DRY rule (see this article by Martin Fowler for example). Therefore, if DRY is about to be violated then something is possibly wrong with the design. And indeed - the interface segregation and single responsibility principles are probably being violated.
Having said this, if you want to stick with this design, you can use a base class:
class MyLibClassDefaultDecoratorBase : ILibInterface
{
protected LibClass backingObject;
public MyLibClassDefaultDecoratorBase(LibClass obj)
{
this.backingObject = obj;
}
// have them all here
public method1() { return this.backingObject.method1(); }
public method2() { return this.backingObject.method2(); }
//...
}
And then your subsequent decorators can alter only the methods they want:
class MyLibClassSimpleDecorator1 : MyLibClassDefaultDecoratorBase
{
public MyLibClassSimpleDecorator1(LibClass obj)
: base(obj)
{
}
public override method1() { /* ... */ }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With