Adapter Pattern in C#
This is the seventh chapter of “Head First Design Patterns” book.
The problem
Accidentally a Turkey’s egg falls among that of Ducks’ and the child tries hard to “adapt” with its duck siblings. How should it adapt?
Simplifying the huge list of behavourial changes the Turkey needs to undergo to two.
- It can fly.
- It makes a quack sound.
- It can fly but for shorter distances
- It makes a gobble sound.
Sounds like this is an adaptation of the Ugly Duckling story right?
Thought process
- We need to create a new implementation such that it emulates the behaviour of a Duck but uses underlying behaviour of the Turkey itself.
UML Class Diagram
You can think the Client
as the mother (matriarch) which tries to teach the ways of duck (Target
interface) to the turkey Adapter
on top of its true self Adaptee
.
Takeaways
The book defines,
The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets class work together that couldn’t otherwise because of incompatible interfaces.
Language specifics
- Since there’s no concept of multiple inheritance in C#, we are using object adapters.
Output
The Turkey says...
Gobble gobble
I'm flying a short distance
The Duck says...
Quack
I'm flying
The TurkeyAdapter says...
Gobble gobble
I'm flying a short distance
I'm flying a short distance
I'm flying a short distance
View all the code in my Github repository.