Python Design Patterns Tutorial
Python Design Patterns Resources
Selected Reading
- Exception Handling
- Python Design Patterns - Anti
- Concurrency in Python
- Strings & Serialization
- Python Design Patterns - Queues
- Python Design Patterns - Sets
- Lists Data Structure
- Dictionaries
- Python Design Patterns - Iterator
- Object Oriented Concepts Implementation
- Object Oriented
- Abstract Factory
- Python Design Patterns - Flyweight
- Python Design Patterns - Template
- Python Design Patterns - Strategy
- Python Design Patterns - State
- Python Design Patterns - Observer
- Chain of Responsibility Pattern
- Python Design Patterns - Proxy
- Python Design Patterns - Decorator
- Python Design Patterns - Adapter
- Python Design Patterns - Command
- Python Design Patterns - Facade
- Python Design Patterns - Prototype
- Python Design Patterns - Builder
- Python Design Patterns - Factory
- Python Design Patterns - Singleton
- Model View Controller Pattern
- Python Design Patterns - Gist
- Introduction
- Python Design Patterns - Home
Python Design Patterns Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Python Design Patterns - Singleton
Python Design Patterns - Singleton
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.
How to implement a singleton class?
The following program demonstrates the implementation of singleton class where it prints the instances created multiple times.
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 −
The number of instances created are same and there is no difference in the objects psted in output.
Advertisements