I'm using an external library (which I can't modify) with classes A and B, both having 2 getters named the same (getter1 and getter2).
There is no relationship between A and B, no super class or interface defining the 2 getters.
In my code, I want to create a method with a parameter that can be either of type A and B, on which I want to call the getters (without caring if the passed parameter is an instance of A or of B).
I can declare an interface with getter1 and getter2, but I can't force the classes A and B to implement this interface, since they reside in an external code.
What would be an elegant solution for the method in my code?
I don't want to have 2 identical methods, one with an A parameter, one with a B parameter.
CodePudding user response:
If neither A
nor B
are final
, then you can use the Adapter Pattern.
Create an interface with the desired two methods defined in it, e.g. Adapter
.
interface Adapter {
String getter1();
String getter2();
}
Create subclasses of A
and B
that each implement Adapter
.
public class AAdapter extends A implements Adapter {}
public class BAdapter extends B implements Adapter {}
Then your method can take an object of type Adapter
.
If you can't do the above because at least one of them is final
, then you'll have to use composition over inheritance. Don't subclass A
and B
, but wrap them in an Adapter class.
class AAdapter implements Adapter {
A a;
public AAdapter(A a) { this.a = a;}
@Override public String getter1() {
return a.getter1();
}
@Override public String getter2() {
return a.getter2();
}
}
class BAdapter implements Adapter {
B b;
public BAdapter(B b) { this.b = b;}
@Override public String getter1() {
return b.getter1();
}
@Override public String getter2() {
return b.getter2();
}
}
CodePudding user response:
I suggest to create your own classes A' and B' which implement same interface with methods that both classes share. Each class should contain an instance of corresponding library class and then simply delegate (by just calling) the method on that class. This way you are not constrained by having methods being called the same. The downside is the extra boilerplate code. But the benefit is that you can adapt a third library (eg. C) if you need to very easy.
Search for "delegate pattern" for more info.