Friday, August 03, 2007

Pattern Series - Part III - Adapter Pattern

Adapter Pattern

Intent:
The Adapter pattern allows otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the clients.

Also known as: Wrapper

Example:
If we are having a two-pin plug point in our switch board, and we are having electronic equipment with three-pin plug pointer, we can use an adapter as interface to fulfill the need.

Class diagram:
A class adapter uses multiple inheritance to adapt one interface to another:


An object adapter relies on object composition:




Participants:

The classes and/or objects participating in this pattern are:
Target : Defines the domain-specific interface that Client uses.
Adapter : Adapts the interface Adaptee to the Target interface.
Adaptee : Defines an existing interface that needs adapting.
Client : Collaborates with objects conforming to the Target interface.


Sample Code:

using System;

class MainApp
{
static void Main()
{
Target target = new Adapter();
target.Request();
Console.Read();
}
}

class Target
{
public virtual void Request()
{
Console.WriteLine("Called Target Request()");
}
}

class Adapter : Target
{
private Adaptee adaptee = new Adaptee();
public override void Request()
{
adaptee.SpecificRequest();
}
}

class Adaptee
{
public void SpecificRequest()
{
Console.WriteLine("Called SpecificRequest()");
}
}

Hope, you could have understand something about Adapter pattern by this time. Meet you with one more pattern soon.

Cheers till then.....

Happy coding....

:))

No comments:

Post a Comment