Hello World


Tuesday, December 11, 2007

Adapter Design Pattern

Convert the interface of a class into another interface clients expect.

Imagine travelling anywhere in the world and be able to plug in your appliances to the power point of the local hotel without any problems with the plug connection.

Doesn't happen right. You need an Adapter.
Adapters are a small plug with two different interfaces, one for our appliance and the other for the local power outlet.
The Adapter allows us to use the Hair dryer that we bought in Australia and dry our hair in England for example, simply because we adapted to the interface.

Same goes with Software adapters, they take one interface and convert it to something that the receiving interface expects.

Some refer to Adapters as Wrappers.

Example:
How to make sure the HairDryer Turns on when we plug into Hotels Socket.
The code demonstrates the Adapter pattern which maps the interface of one class onto another so that they can work together.
The Key is the HairDryerAdapter
If we have any more appliances we just implement a new Adapter
Inheriting from the IEnglandHotelsocket interface.

namespace Martins.Adapter.Pattern
{
class WorkingHairDryer
{
static void Main(string[] args)
{
//Create a HairDryer object
HairDryer dryer= new HairDryer();
//Create a HairDryerAdapter
//and pass in the HairDryer reference
//and return a IEnglandHotelsocket reference

IEnglandHotelsocket dryerAdapter = new HairDryerAdapter(dryer);

//The dryer reference is our Hair Dryer
//The IEnglandHotelsocket is the Hotel power outlet.
//The HairDryerAdapter is the Adapter that connects the two.

//Use the IEnglandHotelsocket interface to call the
//correct Power method for the type
dryerAdapter.GiveMePower();
}
}
public interface IEnglandHotelsocket
{
void GiveMePower();
}
public interface IAustralianAppliance
{
void PowerOn();
}
public class HairDryer: IAustralianAppliance
{
public void PowerOn()
{
Console.WriteLine("BZZZZZZZZZZZ");
}
}
public class HairDryerAdapter : IEnglandHotelsocket
{
IAustralianAppliance dryer;

public HairDryerAdapter(IAustralianAppliance dryer)
{
this. dryer = dryer;
}
public void GiveMePower()
{
dryer.PowerOn();
}
}
}

No comments:

4GuysFromRolla.com Headlines