Interface input

Is it possible to embed an interface in an existing third-party class that I cannot change? Similar to extension methods, but for an interface (and its implementation for the class that he introduced).

I like to optionally use one of two similar third-party libraries, providing classes similar in both libraries to the same interfaces. So I do not need to convert classes there.

+4
source share
3 answers

I don’t quite understand what you mean when injecting the interface, but you can use the Adapter pattern to achieve this. See Also: http://dofactory.com/Patterns/PatternAdapter.aspx

Create your own interface, then create your own classes that implement the interface that contain / complete third-party classes.

+3
source

As long as you work with interfaces, why not just port classes to your own classes that implement interfaces?

+1
source

You should look at the Decorator Pattern , which allows you to extend the class by composition.

eg. This private class A that implements InterfaceA:

public interface InterfaceA { int A {get; set;} } public sealed Class A : InterfaceA { public int A {get;set;} } 

You can extend InterfaceA and then use decorator class B to encapsulate an instance of class A and provide additional methods.

 public interface MyExtendedInterfaceA : InterfaceA { int B {get;set} } public class B : MyExtendedInterfaceA { private InterfaceA _implementsA = new A(); public int A { get { return _implementsA.A; } set { _implementsA.A = value; } } public int B {get; set;} } 

Alternatively, a class C decorator can add a whole new interface:

 public interface InterfaceC { int MethodC(); } public class C : InterfaceA, InterfaceC { private InterfaceA _implementsA = new A(); public int A { get { return _implementsA.A; } set { _implementsA.A = value; } } public int MethodC() { return A * 10; } } 
0
source

All Articles