Allows you to adapt the interface of one object to another.
As a project evolves, you find you have different problems to solve. Many of
these problems require re-engineering, while others can be solved by reusing
some existing code or object.
Here is the scenario, your application has a predefined interface say
IPrintable
which has the single method
Print(). Your internal objects all already inherit
from the IPrintable interface, so they all have their respective
Print()
method defined.
A few weeks into the project, you find you can use an off the shelf component
ComponentA
to handle a certain functionality. However, all your objects need to be part of
IPrintable
and this off the shelf component doesn't have it and additionally you cannot
modify it since you do not have the source code for the object.
Now What? Here, a simple application of the Adaptor pattern can save the day.
You have probably already written an object based on the adaptor pattern in the
past without even knowing it!
To apply the adaptor pattern, as the name implies, you create your own class
MyClass
inheriting from
ComponentA
and you also inherit the
IPrintable
interface used within your project. You can now use
MyClass
as an
IPrintable
object anywhere in your project, and you can also define the
Print()
to include information from
ComponentA
.
Note: Sometimes it is impossible to apply
inheritance for components, however in such a scenario you can simply make
ComponentA
a private instance of
MyClass.