Member-only story
Easy Types and Generics in Python: the Prototype Pattern — Hacking With Python
The prototype pattern can be used when initializing object is expensive in terms of time and resources. As you see in this article, the use of type-hints and generics make the implementation of this pattern elegant, readable and maintainable.
Introduction
The prototype-pattern is a creational design pattern that allows us to create new objects by cloning existing ones, i.e. the existing objects function as a kind of template. This can save time in some cases when for example an object creation involves some heavy calculation or things like network traffic or database queries.
So what does it look like?
A short explanation:
- The main part is the Prototype interface. This defines a Clone() method which returns a Prototype. We will see in the implementation why this is important.
- There are some concrete classes which implement the Clone() method. In this example there are two, but this could of course be any number.
- Finally there is the Client, the class which needs the concrete classes.
Implementation in Python
We will start with these preliminaries: