Create Variation for an Algorithm Without Changing its Structure using Inheritance
Swift â Problems Catalogue #12
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.
Second, we define the template for the base algorithm and some default implementations for some operations.
Third, we define a SimpleWashingMachine and a Deluxe one and we conform them to the WashingSequenceProtocol.
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 đŹ
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 đ¶