Saturday, November 13, 2010

..........Adaptor Pattern[SD]

Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

During object-oriented developments, some times we have to use an unrelated class along with our existing class hierarchy. The simplest solution is to make a wrapper or adaptor around the foreign class, which is acceptable by the existing class hierarchy. This is what known as the ADAPTOR PATTERN or WRAPPER PATTERN.

Suppose we have a class CClient and COldClass

class CClient
{

public void ClientMethod(IExisting objIExisting)
{
objIExisting.Method();
}

}

class COldClass : IExisting
{
public void Method()
{
}
}

And we are using them like that
public void main()
{
CClient objCClient = new CClient();
objCClient.ClientMethod(new COldClass());
}

We were using that classes in our code, In future we have given another class called CAdoptee. which has it’s own method.

private class CAdaptee
{

public void ForeignMethod()
{
Console.WriteLine("Foreign Adapted Method");
}

}

And we have to use that CAdoptee class with client class and we have to call that method ClientMethod. So how we can do that while ClientMethod except a parameter of type IExisting.
There is a way to do that by introducing a CAdopter class.

priavte class CAdopter: IExisitng
{

private CAdoptee objCAdoptee = new CAdoptee();

public void Method()
{
objCAdoptee.ForeignMethod();
}
}

public void main()
{
CClient objCClient = new CClient();
objCClient.ClientMethod(new CAdopter());
}

No comments:

Followers

Link