Photo by Call Me Fred on Unsplash

Make objects with incompatible interfaces work together

Swift — Problems Catalogue #6

Alex Ilovan
Published in
3 min readJul 22, 2022

--

Problem Definition:

Consider the following scenario. You have to implement an electronics store app that specialises in adapters between different plugs and sockets. The scenario is pretty simple, we have a lot of objects that need to be compatible with other types of objects.

Problem Solution:

Solution — Adapter is a design pattern that allows you to use objects with incompatible interfaces to work together.

This is one of the most straightforward and easy design pattern. Code-wise I’ve preferred to keep it very simple but you can expand on it in every way that you want 🚀

Real-World Usage:

Let’s define a EUSocket and a USPlug with a simple method that only displays what kind of plug/socket require in order to function properly. Clearly, they are not compatible as is.

Plugs & Sockets

Now, let’s define the Adapter. It is a simple class that takes a USPlug and makes it compatible with the EUSocket.

Now, in this example, this design pattern does not look like much but you can perform quite powerful business logic if you need input as data from the US Plug but the method you pass the data through only accepts EU sockets.

Adapter class

In the below image, things will become even more apparent. In the ElectronicsApp class, we only have a method that accepts EU Sockets. Let’s say we cannot do anything about it and we must comply. The only problem is that we only have US Plugs.

As you can see below, we can pass a US Plug object to a method that only accepts EU Sockets by using the Adapter.

This design pattern is very versatile when you need an object with a certain type to pass to a method but you only have other types of objects.

Bringing it all together

From this point on, the sky is the limit 🚀 well…almost.

Of course, this design pattern has its limitations but used in moderation, it’s a great tool in our development toolbox.

This is the sixth article in the Swift Problems Catalogue series in which I’ll tackle general software development problems. The aim is to have a quick reference guide that can be easily accessed when having a design/algorithm dillemma.

Let me know what you think and don’t be shy to share where and when this pattern simplified your coding experience 🎶

--

--

Alex Ilovan
salt&pepper

🚀Head of Mobile Development @S&P 💻Comp. Engineer 🪐Engineering Manager. You can visit at: https://www.linkedin.com/in/alex-ilovan-129161b4/