CSharp - Design Patterns Adapter Pattern

Introduction

Adapter Pattern converts the interface of a class into another interface clients expect.

Adapter Pattern makes classes work together in case of incompatible interfaces.

The most common example of this type is a power adapter.

In the following example, we can easily calculate the area of a rectangle.

We need to supply a rectangle in the GetArea() method to get the area of the rectangle.

To calculate the area of a triangle, we have made an adapter (CalculatorAdapter) for the triangle and we are passing a triangle in its GetArea() method.

The method will treat the triangle like a rectangle, and in turn, calls the GetArea() of the Calculator class to get the area.

Demo

using System;

interface RectInterface
{
    void AboutRectangle();
    double CalculateAreaOfRectangle();
}
class Rect : RectInterface
{
    public double Length;
    public double Width;
    public Rect(double l, double w)
    {//from  w  w  w. ja  v  a 2 s . co  m
        this.Length = l;
        this.Width = w;
    }

    public double CalculateAreaOfRectangle()
    {
        return Length * Width;
    }

    public void AboutRectangle()
    {
        Console.WriteLine("Actually, I am a Rectangle");
    }
}

interface TriInterface
{
    void AboutTriangle();
    double CalculateAreaOfTriangle();
}
class Triangle : TriInterface
{
    public double BaseLength;//base
    public double Height;//height
    public Triangle(double b, double h)
    {
        this.BaseLength = b;
        this.Height = h;
    }

    public double CalculateAreaOfTriangle()
    {
        return 0.5 * BaseLength * Height;
    }
    public void AboutTriangle()
    {
        Console.WriteLine(" Actually, I am a Triangle");
    }
}

class TriangleAdapter : RectInterface
{
    Triangle triangle;
    public TriangleAdapter(Triangle t)
    {
        this.triangle = t;
    }

    public void AboutRectangle()
    {
        triangle.AboutTriangle();
    }

    public double CalculateAreaOfRectangle()
    {
        return triangle.CalculateAreaOfTriangle();
    }
}

class Program
{
    static void Main(string[] args)
    {
        Rect r = new Rect(20, 10);
        Console.WriteLine("Area of Rectangle is :{0} Square unit",
           r.CalculateAreaOfRectangle());
        Triangle t = new Triangle(20, 10);
        Console.WriteLine("Area of Triangle is :{0} Square unit",
           t.CalculateAreaOfTriangle());
        RectInterface adapter = new TriangleAdapter(t);
        //Passing a Triangle instead of a Rectangle
        Console.WriteLine("Area of Triangle using the triangle adapter is :{ 0} Square unit", GetArea(adapter));
    }
    static double GetArea(RectInterface r)
    {
        r.AboutRectangle();
        return r.CalculateAreaOfRectangle();
    }
}

Result