Wednesday, October 03, 2007

* Patterns : Adapter Structural Pattern

Adapter pattern also called as Wrapper pattern lets client adapt a framework/service with different call definitions than what client has been designed for. Clients continue using the original definitions and adapter takes care of transformation.

Consider the class diagram below :

Adapter

Client calls the ClientBase class which is client's default framework. Now Client is supposed to use FrameworkBase which has Print method instead of PrintString method. Now instead of changing the client, an Adapter class is created which take care of transforming the method calls.

Provided the methods in ClientBase are virtual, Adapter class can use ClientBase class as base class to provide the transformation functionality.

public class Adapter : ClientBase
{
    private FrameworkBase frmkBase;

    public Adapter()
    {
        frmkBase = new FrameworkBase();
    }

    public override void PrintString(string str)
    {
        frmkBase.Print(str);
    }
}

The client can make calls in same way just by making sure that instance of Adapter class is used.

public class Client
{
    ClientBase cb1, cb2;
    public void Run()
    {
        cb1 = new ClientBase();
        cb2 = new Adapter();
        cb1.PrintString("Hello");
        cb2.PrintString("Hello");
    }
}

Download full source code from here : Adapter Structural Pattern

No comments:

Post a Comment