The Adapter Pattern

Hello everybody,

today I want to make post about one of design patterns which is called Adapter. There are many articles over the web about this topic, but I hope to bring some clarity in this area.

Before I proceed any further, let me describe situation, when you can need it. One of the cases for consideration can be option, if you have your own class, let's name it A. And then let's say that there is some other class B, which has some needed function for you. For example like this:

How you can deal with this? One of the common ways which many people do, is to use class be directly in your code. For example like this:

Aggregate class B from class A in some kind of function, and do with class B from inside A whatever you want. And that approach has permission to live but with some pros and cons. What are pros? You can mention many, but for me the main benefit is simplicity. You can do just what you want and don't care about some issues like testing, faking. 

What are disadvantages? One of the main disadvantages is tighly copling of your class A to class B, and if will have big desire to use some kind of mocking library, then for your it will be hard to achieve it relatively easy. It will be possible to mock it, but with bigger sacrifices from your side. So how to solve it? To add some layer of abstraction. 

One of the ways how I'll use adapter will be the following:

In that case you will have class A which will be not tightly binded to class B and also SomeNeededFunction will not be tightly binded to your class A.

No Comments

Add a Comment