Photo by Joanna Kosinska on Unsplash

Create Variation for an Algorithm Without Changing its Structure using Inheritance

Swift — Problems Catalogue #12

Alex Ilovan
Published in
3 min readSep 2, 2022

--

Problem Definition:

Consider the following scenario. You have to implement a Washing Machine App đŸ§ș in which a user can choose between different types of machines. From simple types to more deluxe types of washing.

In essence, all types of washing machines follow more or less the same algorithm with some variations in the number or types of steps. The problem here is how we create a general algorithm and from there create variations in a simple way for each and every type of machine that we have.

Problem Solution:

Solution —Template Method — it’s a behavioral design pattern that let’s you define a base algorithm and it’s subclasses override the steps without changing the base structure.

This one is pretty straightforward and quite easy to use.

Real-World Usage:

First, as usual, we start with a protocol đŸ”„ Here we add the headers for the base method and the possible steps.

Figure 1. Washing Sequence Protocol

Second, we define the template for the base algorithm and some default implementations for some operations.

Figure 2 Washing Sequence Protocol Extension

Third, we define a SimpleWashingMachine and a Deluxe one and we conform them to the WashingSequenceProtocol.

Figure 3. Washing Machines

Finally, we bring everything together and as you can see by letting the subclasses handle the concrete implementation while having a default implementation for some operations, we can create a lot of variations of the same algorithm. Simple and sweet 🍬

Figure 4. WashingMachineApp

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/