I have an application that uses 3rd party (external jars) and there are all over the place. say for example I have a method f in some class
public int f(int x){
Y y = new Y(x);
return y.someCalculations();
}
where Y is a class from 3rd party.
Say I want to move to other 3rd party? or make my own implementation of Y how can I decouple the dependence in such a way that I can use any 3rd party I want in the future with no effort.
Thank u in advance
Use adapter pattern to wrap the third party library class into your own interface that you want to expose to the client.
So that the client will directly use the interface that you are exposing and will not have to directly call third party library methods. Note here the client can be classes of your own application or end client. This provides you a way to shield or break interfaces when third party library changes something.
Image courtesy - OODesign

Wrappers used to adopt 3rd parties libraries and frameworks - most of the applications using third party libraries use adapters as a middle layer between the application and the 3rd party library to decouple the application from the library. If another library has to be used only an adapter for the new library is required without having to change the application code.
If the third party library is an implementation of a common specification. e.g. JDBC.
Then the Factory pattern is suitable.
However what you are probably after is the Delegation pattern. Which involves writing wrapper classes around the third party calls delegate to the library, so when the library changes then you just have to rewrite the Wrapper.
public class MyWrapperClass{
private Y y = new Y();
public int someCalculations(int myParam){
y.someCalculations(myParam);
}
}
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