CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 5 of 6 · 2 min read

Telling them apart

Same wrapping, different aim.

Choosing between the patterns

Adapter, Facade and Decorator all wrap something. The aim differs.

Pattern What it wraps What it changes Interface of the wrapper
Adapter One class The interface, to match what the client needs New, the target interface
Decorator One object Adds behaviour The same as the wrapped object
Facade Many classes Makes use simpler New and smaller

HF gives a one-line way to remember it: Adapter converts an interface, Decorator adds responsibilities, Facade simplifies. In a design round, name the aim first. If a third-party class does not match your interface, it is an adapter. If a flow touches many services, it is a facade. If you need to add logging or a surcharge without changing the class, it is a decorator.

A related caution from Level 2, module 7: do not add an adapter for a class you own and can change. Adapters earn their place at the edge of your system, where you do not control the other side.

Interview angle

Answer in your head first, then open it.

What is the Adapter pattern?

A class that translates one interface into the one a client expects, so an incompatible class can be used without changing it.

What is the Facade pattern?

One class that offers a simple interface to a group of classes in a subsystem.

How do they differ from Decorator?

An adapter changes the interface, a facade simplifies several interfaces, and a decorator keeps the interface and adds behaviour.

Check yourself: 1. Which pattern would you use to hide four services behind one call? 2. Which pattern keeps the interface the same?

Words you will meet

Word Meaning
Adapter A class that converts one interface into another
Adaptee The existing class that is being adapted
Target The interface that the client expects
Facade A class giving one simple interface to a subsystem
Subsystem A group of classes that work together on one area