Patterns in Python – Creational
In this section, we will take a look at a few of the common creational patterns. We will start with Singleton, and then go on to Prototype, Builder, and Factory, in that order.
The Singleton pattern
The Singleton pattern is one of the most well-known and easily understood patterns in the entire pantheon of design patterns. It is usually defined as:
A Singleton is a class which has only one instance and a well-defined point of access to it.
The requirements of a Singleton can be summarized as follows:
A class must have only one instance accessible via a well-known access point
The class must be extensible by inheritance without breaking the pattern
The simplest Singleton implementation in Python is shown next. It is done by overriding the
__new__
method of the baseobject
type:# singleton.py class Singleton(object): """ Singleton in Python """ _instance = None def __new__(cls): if cls._instance == None: cls._instance = object...