SlideShare ist ein Scribd-Unternehmen logo
1 von 15
Creational - The
Singleton Design
Pattern
By Ragib Shahriar
What is it ?
The Singleton Design Pattern is a Creational pattern, whose objective is to create only one
instance of a class and to provide only one global access point to that object.
Using a singleton pattern has many benefits. A few of them are:
● To limit concurrent access to a shared resource.
● To create a global point of access for a resource.
● To create just one instance of a class, throughout the lifetime of a program.
A singleton is used in the printer management software to process queries without modification and ultimately print.
credit: www.ionos.com
A class using the singleton design pattern will include,
1. A private static variable, holding the only instance of the class.
2. A private constructor, so it cannot be instantiated anywhere else.
3. A public static method, to return the single instance of the class.
Different ways to implement a Singleton:
A singleton pattern can be implemented in three different ways. They are as follows:
● Module-level Singleton
● Classic Singleton
● Borg Singleton
Module-level Singleton:
All modules are singleton, by definition. Let’s create a simple module-level singleton where
the data is shared among other modules.Here we will create three python files –
singleton.py, module1.py, and module2.py – in which the other sample modules share a
variable from singleton.py.
## singleton.py file
shared_variable = "Shared Variable"
## module1.py file
import singleton
print(singleton.shared_variable)
singleton.shared_variable += "(modified by samplemodule1)"
##module2.py file
import singleton
print(singleton.shared_variable)
Here, the value changed by module1 is also reflected in module2.
Classic Singleton:
Classic Singleton creates an instance only if there is no instance created so far; otherwise, it
will return the instance that is already created.
Let’s take a look at the below code.
class Singleton(object):
def __new__(cls):
if not hasattr(cls, 'instance'):
cls.instance = super(Singleton, cls).__new__(cls)
return cls.instance
output:
Try to subclass the Singleton class with another one.
class Child(Singleton):
pass
If it’s a successor of Singleton, all of its instances should also be the instances of Singleton,
thus sharing its states. But this doesn’t work as illustrated in the following code:
To avoid this situation, the borg singleton is used.
Borg Singleton:
Borg is also known as monostate. In the borg pattern, all of the instances are different, but
they share the same state. In the following code , the shared state is maintained in the
_shared_state attribute. And all new instances of the Borg class will have this state as
defined in the __new__ class method.
class Borg(object):
_shared_state = {}
def __new__(cls, *args, **kwargs):
obj = super(Borg, cls).__new__(cls, *args, **kwargs)
obj.__dict__ = cls._shared_state
return obj
>>> from example1 import Borg
>>> class Child(Borg):
... pass
...
>>> borg = Borg()
>>> new_borg = Borg()
>>> print(borg is new_borg)
False
>>> child = Child()
>>> borg.only_one_var = "I'm the only one var"
>>> child.only_one_var
"I'm the only one var"
Here is how it works with subclassing:
You can use a metaclass if you want to use instance as a property. For example;
class Singleton(type):
# Inherit from "type" in order to gain access to method __call__
def __init__(self, *args, **kwargs):
self.__instance = None # Create a variable to store the object reference
super().__init__(*args, **kwargs)
def __call__(self, *args, **kwargs):
if self.__instance is None:
# if the object has not already been created
self.__instance = super().__call__(*args, **kwargs) # Call the __init__ method of the subclass (Spam) and save the
reference
return self.__instance
else:
# if object (Spam) reference already exists; return it
return self.__instance
class Spam(metaclass=Singleton):
def __init__(self, x):
print('Creating Spam')
self.x = x
if __name__ == '__main__':
spam = Spam(100)
spam2 = Spam(200)
Which type of singleton should be used is up to you?
If you expect that your singleton will not be inherited, you can choose the classic singleton;
otherwise, it’s better to stick with borg.
Reference:
1. https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
2. https://www.geeksforgeeks.org/singleton-pattern-in-python-a-complete-
guide/#:~:text=Singleton%20pattern%20is%20a%20design,of%20access%20for%2
0a%20resource.
3. https://www.geeksforgeeks.org/singleton-method-python-design-patterns/
4. https://refactoring.guru/design-patterns/singleton/python/example#example-1
5. https://www.educative.io/courses/software-design-patterns-best-
practices/B8nMkqBWONo
6. https://hub.packtpub.com/python-design-patterns-depth-singleton-pattern/

Weitere ähnliche Inhalte

Ähnlich wie Creational - The Singleton Design Pattern

Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptAyush Sharma
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objectsSandeep Chawla
 
Singleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation PatternSingleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation PatternSeerat Malik
 
Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Abu Saleh
 
Object Oriented Prograring(OOP) java
Object Oriented Prograring(OOP) javaObject Oriented Prograring(OOP) java
Object Oriented Prograring(OOP) javaGaddafiAdamu1
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design PatternsPham Huy Tung
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming conceptsGanesh Karthik
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design PatternsAddy Osmani
 
Creational Design Patterns.pptx
Creational Design Patterns.pptxCreational Design Patterns.pptx
Creational Design Patterns.pptxSachin Patidar
 

Ähnlich wie Creational - The Singleton Design Pattern (20)

Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
Backbonejs
BackbonejsBackbonejs
Backbonejs
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objects
 
Singleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation PatternSingleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation Pattern
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
python.pptx
python.pptxpython.pptx
python.pptx
 
Java oop concepts
Java oop conceptsJava oop concepts
Java oop concepts
 
Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)
 
Object Oriented Prograring(OOP) java
Object Oriented Prograring(OOP) javaObject Oriented Prograring(OOP) java
Object Oriented Prograring(OOP) java
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
 
Lesson6
Lesson6Lesson6
Lesson6
 
What is design pattern
What is design patternWhat is design pattern
What is design pattern
 
Sda 8
Sda   8Sda   8
Sda 8
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming concepts
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Django Good Practices
Django Good PracticesDjango Good Practices
Django Good Practices
 
C# Unit 2 notes
C# Unit 2 notesC# Unit 2 notes
C# Unit 2 notes
 
Creational Design Patterns.pptx
Creational Design Patterns.pptxCreational Design Patterns.pptx
Creational Design Patterns.pptx
 

Kürzlich hochgeladen

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 

Kürzlich hochgeladen (20)

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 

Creational - The Singleton Design Pattern

  • 1. Creational - The Singleton Design Pattern By Ragib Shahriar
  • 2. What is it ? The Singleton Design Pattern is a Creational pattern, whose objective is to create only one instance of a class and to provide only one global access point to that object. Using a singleton pattern has many benefits. A few of them are: ● To limit concurrent access to a shared resource. ● To create a global point of access for a resource. ● To create just one instance of a class, throughout the lifetime of a program.
  • 3. A singleton is used in the printer management software to process queries without modification and ultimately print. credit: www.ionos.com
  • 4. A class using the singleton design pattern will include, 1. A private static variable, holding the only instance of the class. 2. A private constructor, so it cannot be instantiated anywhere else. 3. A public static method, to return the single instance of the class.
  • 5. Different ways to implement a Singleton: A singleton pattern can be implemented in three different ways. They are as follows: ● Module-level Singleton ● Classic Singleton ● Borg Singleton
  • 6. Module-level Singleton: All modules are singleton, by definition. Let’s create a simple module-level singleton where the data is shared among other modules.Here we will create three python files – singleton.py, module1.py, and module2.py – in which the other sample modules share a variable from singleton.py. ## singleton.py file shared_variable = "Shared Variable" ## module1.py file import singleton print(singleton.shared_variable) singleton.shared_variable += "(modified by samplemodule1)"
  • 7. ##module2.py file import singleton print(singleton.shared_variable) Here, the value changed by module1 is also reflected in module2.
  • 8. Classic Singleton: Classic Singleton creates an instance only if there is no instance created so far; otherwise, it will return the instance that is already created.
  • 9. Let’s take a look at the below code. class Singleton(object): def __new__(cls): if not hasattr(cls, 'instance'): cls.instance = super(Singleton, cls).__new__(cls) return cls.instance output:
  • 10. Try to subclass the Singleton class with another one. class Child(Singleton): pass If it’s a successor of Singleton, all of its instances should also be the instances of Singleton, thus sharing its states. But this doesn’t work as illustrated in the following code: To avoid this situation, the borg singleton is used.
  • 11. Borg Singleton: Borg is also known as monostate. In the borg pattern, all of the instances are different, but they share the same state. In the following code , the shared state is maintained in the _shared_state attribute. And all new instances of the Borg class will have this state as defined in the __new__ class method.
  • 12. class Borg(object): _shared_state = {} def __new__(cls, *args, **kwargs): obj = super(Borg, cls).__new__(cls, *args, **kwargs) obj.__dict__ = cls._shared_state return obj >>> from example1 import Borg >>> class Child(Borg): ... pass ... >>> borg = Borg() >>> new_borg = Borg() >>> print(borg is new_borg) False >>> child = Child() >>> borg.only_one_var = "I'm the only one var" >>> child.only_one_var "I'm the only one var" Here is how it works with subclassing:
  • 13. You can use a metaclass if you want to use instance as a property. For example; class Singleton(type): # Inherit from "type" in order to gain access to method __call__ def __init__(self, *args, **kwargs): self.__instance = None # Create a variable to store the object reference super().__init__(*args, **kwargs) def __call__(self, *args, **kwargs): if self.__instance is None: # if the object has not already been created self.__instance = super().__call__(*args, **kwargs) # Call the __init__ method of the subclass (Spam) and save the reference return self.__instance else: # if object (Spam) reference already exists; return it return self.__instance class Spam(metaclass=Singleton): def __init__(self, x): print('Creating Spam') self.x = x if __name__ == '__main__': spam = Spam(100) spam2 = Spam(200)
  • 14. Which type of singleton should be used is up to you? If you expect that your singleton will not be inherited, you can choose the classic singleton; otherwise, it’s better to stick with borg.
  • 15. Reference: 1. https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python 2. https://www.geeksforgeeks.org/singleton-pattern-in-python-a-complete- guide/#:~:text=Singleton%20pattern%20is%20a%20design,of%20access%20for%2 0a%20resource. 3. https://www.geeksforgeeks.org/singleton-method-python-design-patterns/ 4. https://refactoring.guru/design-patterns/singleton/python/example#example-1 5. https://www.educative.io/courses/software-design-patterns-best- practices/B8nMkqBWONo 6. https://hub.packtpub.com/python-design-patterns-depth-singleton-pattern/