Friday, July 16, 2010

Design Patterns: Adapter

Let's say you are working on an application which has different layers (upper layers are using the lower layers). Now there is a new requirement, and you have to add a new component to the lower layer but you will realize that there is already an "older piece of code" that does the same functionality, so instead of implementing a new component from scratch you want to use this older code, but the problem with the older code is that it does not completely follow the specification of your application and you can not simply drop it into your existing code. This is a perfect scenario to use an "Adapter", A piece of code that encapsulates that older code and exposes its functionality in terms of the interface that is in place.

Major Players of this pattern are:

  • Target (An abstract base class for the adapters)

  • Adapter

  • Adaptee (The older piece of code)

  • Client



The idea is common in .NET framework, for example every time you use a legacy COM component and import it into .NET, what happens is that the imported code will be wrapped inside an adapter .NET class (interop assembly) that translates the functionality and patterns that were common in the COM era to the .NET era. For example if a method fails to operate properly in COM, it will return a non-zero HRESULT value; this functionality is changed by the adapter (interop assembly) to raise an exception instead (which is more common in .NET)


class Program
{
static void Main(string[] args)
{
//The client has no idea about the older code
Target target = new Adapter();
target.NewerMethod();
}
}

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

// The actual "Adapter"
class Adapter : Target
{
//Points to the older piece of code
private Adaptee adaptee = new Adaptee();

public override void NewerMethod()
{
adaptee.OlderMethod();
}
}

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

No comments:

Post a Comment