Adapter coding pattern with C-Sharp

Written on Mar 02, 2016

Adapter pattern is one of Gang of Four patterns which falls under structural pattern. Its working model is based on working on electronic adapter, which is to level the voltages of machine and power source. Same concept applies here, there are some occurances when we have 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 which'll implement that interface base class and internally it calls that third party library code.

To understand adapter method in more details, let's take one real life scenario. Let's say i have one third party class library to get file details through FTP, As below.

Well, i have one interface in my project for accessing any file related methods like below.

Now coming to problem, i can not add interface inheritance to FTPFileAccess class because it is thid party code library. So, in order to make interface object access methods of FTPFileAccess class, i need to add adapter class like below.

My final top level access code will be like below.

Moral of adapter coding pattern is to create extra adapter classes, as and when required which inherits standard interfaces and internally they call necessary thid party class library and finishes task.

In general, adapter pattern uses some terms likes Client, Target, Adapter and Adaptee. In this case my final level call to interface would be my client. Target is through which client accesses method, without knowing any implementations. So in this case IFileAccess interface, will be target. Here class FTPFileAccessAdapter will be adapter and my third party code library FTPFileAccess will be my adaptee.

Following is my full source code.

Output will be as below.