by Leon Rosenshein

Adapters, Facades, and Decorators - Oh My

The GOF gave us Design Patterns in 1994. It's been helping and confusing folks ever since. There's good high level advice and a bunch of patterns that can be reused. The confusion comes around because some of them are very similar, but as usual, the details are important.

Consider the adapter, facade, and decorator patterns. All of them take existing functionality and wrap it, changing the interface slightly. So why are there 3 different patterns and which one should you use? The answer is, it depends. It depends on why you're doing whatever it is you're doing.

The simplest is the adapter. Consider a trip from the US to EMEA. You've got a bunch of electronics with you, and you'd like to be able to plug them in wherever you are. So you carry a bunch of adapters with you. They're just lumps of copper and insulator, carefully designed to allow you to plug your device in on one end and into the wall on the other. It just changes the shape of the plug. If you're in Austria the outlet has 220V, 50hz, and that's what goes into and out of the adapter. Hopefully your device can handle it. Software adapters are the same. All of the same parameters go in/out, and they're not modified on the way through. The purpose is to allow you to adapt one system to fit another, but the functionality/meaning better match, or else.

Next is the facade. Facades are false fronts, and make things simpler to use. If your API offers 20 different flags and options, but really you only care about changing one of them you might make a facade that takes that one parameter, adds your own defaults, and then passes it on. Back to the power adapter analogy, consider the Qi charging on your phone. Instead of plugging in a 24 pin USB-C connector you throw your phone onto the charger and get more power. Very simple, but you lose the ability to transfer data.

Finally, there's the decorator. What do you do if your US electronics can't handle 220V at 50 Hz? Then you need a decorator. Sure, on the surface it looks like an adapter, but under the covers it has a transformer and frequency converter. Plug it in to an Austrian wall socket and you can plug your US device in and, if it's a good decorator, the device will never know. Software decorators are the same thing. They add functionality. If you have a data source that uses push to send its data and a sync that uses pull you need something between them. One example might be a statsd metrics exporter (push) and a Prometheus Time series dB (pull). You need a decorator between them if you want them to talk to each other. The decorator would take the push from the service, buffer it, then respond to the Prometheus pull. So not entirely unlike an adapter, but more.