Skip to content

Instantly share code, notes, and snippets.

@aj07mm
Forked from pazdera/gist:1098129
Created March 28, 2019 00:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aj07mm/15cb83ac62b7bc6771b28895cd2a2226 to your computer and use it in GitHub Desktop.
Save aj07mm/15cb83ac62b7bc6771b28895cd2a2226 to your computer and use it in GitHub Desktop.
Singleton example in Python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Example of Singleton design pattern
# Copyright (C) 2011 Radek Pazdera
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class Singleton:
# Here will be the instance stored.
__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
# A little testing
s = Singleton() # Ok
#Singleton() # will raise exception
print s
s = Singleton.getInstance()
print s
s = Singleton.getInstance()
print s # will print the same instance as before
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment