The adapter pattern is one of the Gang of Four patterns that falls under a structural pattern. Its working model is based on working on an electronic adapter, which is to level the voltages of the machine and power source. The same concept applies here.
There are some occurrences when we have a third-party library or any other code which we can not access using our standard interface base class. At that time we’ll create one adapter class that implements that interface base class and internally it calls that third-party library code.
To understand the adapter method in more detail, let’s take one real-life scenario. Let’s say I have one third-party class library to get file details through FTP.
The code is located below.
Well, I have one interface in my project for accessing any file-related methods like below.
Now coming to the problem, I can not add interface inheritance to FTPFileAccess class because it is a third-party code library. So, in order to make interface object access methods of FTPFileAccess class, I need to add an adapter class.
Access the code here.
My final top-level access code will be like here below.
The moral of the adapter coding pattern is to create extra adapter classes, as and when required which inherits standard interfaces, and internally they call the necessary third-party class library and finish the task.
In general, the adapter pattern uses some terms like Client, Target, Adapter, and Adaptee. In this case, my final level call to the interface would be my client. Target is through which client accesses method, without knowing any implementations. So in this case IFileAccess interface will be the target. Here class FTPFileAccessAdapter will be adapter and my third-party code library FTPFileAccess will be my adaptee.
Following is my full source code.
The output will be as below.