Prototype pattern in Swift

Well, another great gap between my posts but once I lose my rhythm it’s hard to come back. 😢 Well I’ve got to try harder. 💪 So there is only two more Constructional Patterns before us the Prototype and the Singleton, and today I will describe the former one.

The problem with constructional patterns at least for me is that basically you can use them in conjunction, separately or implement them with one using another. Every one of them has its pros and cons and it requires great amount on experience and knowledge to use fluently (except the Sigleton, that one is really easy to implement and you should be careful not to use it too much, but about that in the next episode). Enough off topic 🤐.

What for?

So, as with all patterns which I described before we will be constructing objects and there are few insights which may help you when deciding on the Prototype pattern. First of all you should consider choosing it when your application should be independent from the method of creating, compositing and representing your objects plus at least one of following:

  • Objects are created on runtime
  • You want to avoid complex hierarchies of factories
  • Objects can have only few states

How does it work? Well kind of simple. You just have to ask prototype to clone itself 😄😄.

Again as with previous examples (Abstract Factory and Builder) it is a little bit challenging for me to come up with examples.

Implementation

Single most important thing about prototype classes is the clone method they should have. If you see hierarchy of product with clone method in use, you are looking at Prototype pattern.

Let’s define key actors of this play before we jump into the code sample.

Prototype- (Game) declaration of interface, especially clone() -> Game method

ConcretePrototype- (BasketballGame & FootballGame) implementation of cloning process

Client- that one is really simple. Just clones stuff 👥

So as you can see it is a really object oriented design pattern. I am going to tweak it (and others) some more to adapt it to modern Swift programming so stay tuned, but basically we get copy style behavior for free with value types (struct all the things 🤘).

So I hope you enjoyed this short article. As always I welcome every feedback and will be happy to discuss it (and other things) anywhere. New articles should appear more frequently in upcoming weeks and the next one is…

… the one and only Singleton