Photo by henry perks on Unsplash

Attach new behaviours to objects

Swift — Problems Catalogue #10

Alex Ilovan
Published in
3 min readAug 19, 2022

--

Problem Definition:

Consider the following scenario. You have to implement a Screwdrivers Collection App ✨🪛

But wait! These are not your typical screwdrivers. They are a work of art and they can be as futuristic as a Laser Screwdriver or a Sonic Screwdriver (Dr Who vibes much?) or even a Laser Sonic Screwdriver 😮

I think you already know where this leads. The question is how can we create a base, standard object and just attach as many features as we want in a clean and easy way?

Problem Solution:

Solution —Decorator it’s a structural design pattern that let’s you attach new behaviours to objects, using wrapper objects called decorators.

I think this is one of my favourite solutions because it feels very Swiftly.

Real-World Usage:

Let’s start by creating our base object using a protocol called Screwdriver with a simple operation called screw().

Afterwards, let’s create a ConcreteScrewdriver that conforms to the above protocol and implement its screw() method.

Figure 1. Screwdriver

Next, let’s create our base ScrewDecorator that conforms to our Screwdriver protocol, takes a screwdriver object and implements its screw() method by executing its screwdriver’s object screw() method. From here you can start to feel where this is going.

Afterwards, let’s create our actual decorators, a sonic one and a laser one and conform them to the base ScrewDecorator. By overriding its base’s screw() method and calling its parent’s screw() method, you can attach as many traits as you want.

Best practice says to create a decorator for every trait you want to create. Just to keep everything nice and neat.

Figure 2. Decorators

Finally, let’s create a custom class with a test() method that can test our screwdrivers and a ScrewdriverApp class that brings everything together.

As you can see in Figure 3, you can construct a base screwdriver and attach as many behaviours as you want. In the end, the final result will be that the customer will Screw using a Laser Sonic Screwdriver.

Figure 3. Bringing everything 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 next 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/