Adapter Pattern in C#


Most of you might have heard about the Adapter Pattern. It is a pattern commonly used in our applications but without knowing it. The Adapter Pattern is one among the 23 Design Patterns.

Challenge

You are working on a Square class. You need to find the Area of it using Calculator class. But the Calculator class only takes Rectangle class as input. How to solve this scenario?

Adapter Pattern

Definition

"Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces."

Implementation

Following are the class definitions for Rectangle and Calculator.

    public class Rectangle
    {
        public int Width;
        public int Height;
    }
 
    public class Calculator
    {
        public int GetArea(Rectangle rectangle)
        {
            int area = rectangle.Width * rectangle.Height;
 
            return area;
        }
    }


As we cn see from the above example an instance of Rectangle is needed to calculate the area. If we have a square class of definition below, the calculation cannot be done.
   
   
public class Square
    {
        public int Size;
    }

Here we have to create a new CalculatorAdapter to get the work done.

    public class CalculatorAdapter
    {
        public int GetArea(Square square)
        {
            Calculator calculator = new Calculator();
           
            Rectangle rectangle = new Rectangle();
            rectangle.Width = rectangle.Height = square.Size;
 
            int area = calculator.GetArea(rectangle);
 
            return area;
        }
    }


The CalculatorAdapter performs the following functions:

  • Takes the Square parameter
  • Convert Square to Rectangle
  • Call the original Calculator.GetArea() method
  • Return the value received

The invoking code is shown below:

   
// Create Square class and assign Size from UI
    Square square = new Square();
    square.Size = SquarePanel.Width;
 
   
// Use Adapter to calculate the area
    CalculatorAdapter adapter = new CalculatorAdapter();
    int area = adapter.GetArea(square);
 
   
// Display the result back to UI
    ResultLabel.Text = "Area: " + area.ToString();


On running the sample application we can see the following results.

Adapter Pattern in C#

Note: We can have other examples including Interfaces to show the above pattern. For simplicity I have avoided the interfaces. In real life the AC to DC adapter is an example of the Adapter pattern as it makes the incompatible device and power supply work together.

Summary

In this article we have explored Adapter pattern. This pattern is useful in scenarios where incompatible types are dealt with. The associated source code contains the example application we have discussed.

Up Next
    Ebook Download
    View all
    Learn
    View all