We've seen quite a few patterns so far, and I'm glad so many people like them. They turned out to be the most popular posts I've ever written when it comes to development. Thanks! :)
A little overview for the late joiners:
- Long Absence - Design Patterns
- Design Patterns - Strategy Pattern
- Design Patterns - Observer Pattern
- Design Patterns - Observer/Event Pattern
- Design Patterns - Decorator Pattern
- Design Patterns - Factory Method Pattern
- Design Patterns - Abstract Factory Pattern
- Design Patterns - Singleton Pattern
- Design Patterns - Generic Singleton Pattern
- Design Patterns - Command Pattern
Today we'll have a look at the Adapter Pattern.
As usual, the definition: "Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces."
To continue on our little game, we received a third party library from another team, containing some buildings to include in our game. The developers of this library didn't work with IBuildings however, but call it a Structure, making all of our code which interacts with IBuilding unusable.
If we look at the definition, we can see the Adapter Pattern is the perfect solution for this, since we need to convert the interface of the third party Structure into the IBuilding we expect, so that they can work together as if their interface was compatible.
Let's have a look on how their interface looks like first.
There are some differences in the logic used in their implementation. We both have a Description, but the way we manage Power consumption is totally different.
Time to adapt their interface to the one we expect. We'll do this by creating a new class, a so called adapter, which implements the IBuilding interface, since we expect that one, and which uses composition to encapsulate a Structure.
As you can see, our Adapter is actually behaving as an IBuilding to the rest of our code, adapting the calls to our interface into the third party their interface. And that's it really! The easiest way I remember this pattern is by thinking of electrical adapters, changing the socket from US to UK, or transforming the voltages.
Time to have a look at the full diagram, with the official names written against it again:
Let's also write some test code to see the Adapter Pattern in action.
We can re-use all of our existing code with the new Structures, since it's behaving like an IBuilding right now.
I've uploaded the solution again to have a look at.
Some additional information on the Adapter Pattern: