Click here to Skip to main content
Click here to Skip to main content

Adapter Design Pattern in C#

, 7 Mar 2014
Rate this:
Please Sign up or sign in to vote.
Adapter Design Pattern in C#

Introduction

This trick is about how to implement the Adapter design pattern in C#.

Background

Design patterns are general reusable solutions to common problems that occurred in software designing. There are broadly 3 categories of design patterns, i.e., Creational, Behavioral and Structural.

Adapter design pattern comes under the category of Structural Design pattern.
It is a design pattern that translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface.

(Source: Adapter Pattern)

Using the Code

The adapter pattern is useful when we need to implement the new functionality without disturbing the existing function or if we do not have access to the existing code, i.e., we can only call that function.
The code below illustrates the example:

  1. Suppose, there is a class: Adaptee with function ExistingFunction() as shown below:
     // Existing Function that we need to use
        class Adaptee
        {
    
            public string ExistingFunction()
            {
              //Some Processing 
               return "Some Output String";
            }
        }
  2. Please note that the above function returns some specific string. Now we want to communicate with the above class with our interface and want to do the same processing that ExistingFunction is doing. But we want some custom output string. For this, we need the following code.

    Below is the Target Interface:

     // Target Interface that need to use 
        interface ITarget
        {
    
            string CustomFunction();
        }

    Now, below is the Adapter class which provides the communication between Adaptee class and target Interface:

         // Implementing the required new function
        class Adapter : Adaptee, ITarget
        {
            public string CustomFunction()
            {
                return "New output: " + ExistingFunction();
            }
        }

    Finally, the Client code looks like:

         Adapter objAdaptor = new Adapter();
         string sStr = objAdaptor.CustomFunction();

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Vipin_Arora
Software Developer (Senior)
India India
Linkedin profile: http://www.linkedin.com/profile/view?id=241442098
Follow on   LinkedIn

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 7 Mar 2014
Article Copyright 2014 by Vipin_Arora
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid