Adapter Pattern in C#

Srinjoy Santra
2 min readFeb 25, 2023

This is the seventh chapter of “Head First Design Patterns” book.

Photo by Call Me Fred on Unsplash

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.

Mallard Duck:

  • It can fly.
  • It makes a quack sound.

Wild Turkey:

  • It can fly but for shorter distances
  • It makes a gobble sound.

Sounds like this is an adaptation of the Ugly Duckling story right?

Ugly Duckling Story

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.

Make different candidates “adapt” to the standardized tests

Do you see a mistake in there? Mention in the comments.

Did you like it? Show your support through claps 👏.

I’m Srinjoy Santra, currently an SDE-1 at BookMyShow. You can connect with me on LinkedIn, visit my Github account, or follow me on Twitter.

--

--