- Python Design Patterns - Home
- Python Design Patterns - Introduction
- Python Design Patterns - Gist
- Model View Controller Pattern
- Python Design Patterns - Singleton
- Python Design Patterns - Factory
- Python Design Patterns - Builder
- Python Design Patterns - Prototype
- Python Design Patterns - Facade
- Python Design Patterns - Command
- Python Design Patterns - Adapter
- Python Design Patterns - Decorator
- Python Design Patterns - Proxy
- Chain of Responsibility Pattern
- Python Design Patterns - Observer
- Python Design Patterns - State
- Python Design Patterns - Strategy
- Python Design Patterns - Template
- Python Design Patterns - Flyweight
- Python Design Patterns - Abstract Factory
- Python Design Patterns - Object Oriented
- Object Oriented Concepts Implementation
- Python Design Patterns - Iterator
- Python Design Patterns - Dictionaries
- Python Design Patterns - Lists Data Structure
- Python Design Patterns - Sets
- Python Design Patterns - Queues
- Python Design Patterns - Strings & Serialization
- Python Design Patterns - Concurrency
- Python Design Patterns - Anti Pattern
- Python Design Patterns - Exception Handling
Python Design Patterns Resources
Python Design Patterns - Singleton Pattern
This pattern restricts the instantiation of a class to one object. It is a type of creational pattern and involves only one class to create methods and specified objects.
It provides a global point of access to the instance created.
Example - How to implement a singleton class?
The following program demonstrates the implementation of singleton class where it prints the instances created multiple times.
main.py
class Singleton:
__instance = None
@staticmethod
def getInstance():
""" Static access method. """
if Singleton.__instance == None:
Singleton()
return Singleton.__instance
def __init__(self):
""" Virtually private constructor. """
if Singleton.__instance != None:
raise Exception("This class is a singleton!")
else:
Singleton.__instance = self
s = Singleton()
print(s)
s = Singleton.getInstance()
print(s)
s = Singleton.getInstance()
print(s)
Output
The above program generates the following output −
<__main__.Singleton object at 0x7f7cb4e32d50> <__main__.Singleton object at 0x7f7cb4e32d50> <__main__.Singleton object at 0x7f7cb4e32d50>
The number of instances created are same and there is no difference in the objects listed in output.
Advertisements