Member-only story

Easy Types and Generics in Python: the Prototype Pattern — Hacking With Python

Iede Snoek
3 min readOct 21, 2023

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:

  1. 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.
  2. There are some concrete classes which implement the Clone() method. In this example there are two, but this could of course be any number.
  3. Finally there is the Client, the class which needs the concrete classes.

Implementation in Python

We will start with these preliminaries:

--

--

Iede Snoek
Iede Snoek

Written by Iede Snoek

A love of music and of programming, that is what makes me tick, over 25 years of experience in IT, and a lifelong love of music is what makes me live.

No responses yet