8
The Singleton Pattern
The Singleton pattern is grouped with the other creational patterns, although, to some extent, it is a “noncreational” pattern. There are any number of cases in programming where you need to make sure that there can be one, and only one, instance of a class. For example, your system can have only one window manager or print spooler, as well as a single point of access to a database engine.
Python does not directly have a feature where a single static variable will be accessible from all class instances, so a simple flag won’t work. Instead, this technique utilizes two subtle Python features you might not be aware of: the static
method and the __instance
variable.
Python has a Decorator that tells the compiler to make ...
Get Python Programming with Design Patterns now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.