Tuesday, October 30, 2012

Adapter Pattern

Well I think the best way to describe an adapter pattern is to visualize an adapter we used in our 8 bit video games. Remember that the power cable is not called a power cable anymore. The reason I am telling that example is because that’s the first time I saw an adapter. Nowadays the radios, CD players everything haa adapters and you already know what that do.

The power mains in our house is of 220V/110V (India/USA) but the players want a power or 8V or something to run. So what to do, use an adapter.

In a very similar manner, think of the interfaces in the software. What our adapter will do is

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



Simple enough, isn’t it. Now lets try to visualize it



Now if we look at an example lets say we have an old class in which we have two functions to introduce oneself and greet.

class OldClass
{
public:
void Greet()
{
cout<<"Happy new yeat"; } void IdentifyYourself() { cout<<"My name is earl"; } }; But in our new interface we only want to use the funciion IdentifyNGreet and not two different function. class newClient { public: void IdentifyNGreet() { } }; So what we will do is we will do, we will introduce an adapter in between. class IAdapter { public: virtual void IdentifyNGreet() = 0; }; class Adapter : public IAdapter { public: void IdentifyNGreet() { old.IdentifyYourself(); cout<< "\n"; old.Greet(); } private: OldClass old; }; And our new class will then look something like class newClient { public: void IdentifyNGreet() { Adapter ad; ad.IdentifyNGreet(); } }; Now we have placed an adapter in between our old and new class and now we can simply use our new class whenever required newClient client; client.IdentifyNGreet(); Now lets try to identify when should we use the adapter pattern Indicators in analysis: Normally don’t worry about interfaces here, so don’t usually think about it. However, if you
know some existing code is going to be incorporated into your system, it is likely that an adapter will be needed since
it is unlikely this pre-existing code will have the correct interface.
Indicator in design: Something has the right stuff but the wrong interface. Typically used when you have to make
something that’s a derivative of an abstract class we are defining or already have.
Field notes: The adapter pattern allows you to defer concern about what the interfaces of your pre-existing objects
look like since you can easily change them.

I think this much talk about adapter is good enough to understand the theory and get a basic idea of what needs o be done in adapter pattern. So lets call it an article for now.

No comments:

Post a Comment