]> git.decadent.org.uk Git - dak.git/blob - daklib/Singleton.py
456d2ccdf3b970370623c1ecd1e58ad0a55be268
[dak.git] / daklib / Singleton.py
1 #!/usr/bin/env python
2 # vim:set et ts=4 sw=4:
3
4 # Singleton pattern code
5 # Copyright (C) 2008  Mark Hymers <mhy@debian.org>
6
7 # Inspiration for this very simple ABC was taken from various documents /
8 # tutorials / mailing lists.  This may not be thread safe but given that
9 # (as I write) large chunks of dak aren't even type-safe, I'll live with
10 # it for now
11
12 ################################################################################
13
14 # This program is free software; you can redistribute it and/or modify
15 # it under the terms of the GNU General Public License as published by
16 # the Free Software Foundation; either version 2 of the License, or
17 # (at your option) any later version.
18
19 # This program is distributed in the hope that it will be useful,
20 # but WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 # GNU General Public License for more details.
23
24 # You should have received a copy of the GNU General Public License
25 # along with this program; if not, write to the Free Software
26 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27
28 ################################################################################
29
30 # < sgran> NCommander: in SQL, it's better to join than to repeat information
31 # < tomv_w> that makes SQL the opposite to Debian mailing lists!
32
33 ################################################################################
34
35 """
36 This class set implements objects that may need to be instantiated multiple
37 times, but we don't want the overhead of actually creating and init'ing
38 them more than once.  It also saves us using globals all over the place
39 """
40
41 class Singleton(object):
42     """This is the ABC for other dak Singleton classes"""
43     __single = None
44     def __new__(cls, *args, **kwargs):
45         # Check to see if a __single exists already for this class
46         # Compare class types instead of just looking for None so
47         # that subclasses will create their own __single objects
48         if cls != type(cls.__single):
49             cls.__single = object.__new__(cls, *args, **kwargs)
50             cls.__single._startup(*args, **kwargs)
51         return cls.__single
52
53     def __init__(self, *args, **kwargs):
54         if type(self) == "Singleton":
55             raise NotImplementedError("Singleton is an ABC")
56
57     def _startup(self):
58         """
59         _startup is a private method used instead of __init__ due to the way
60         we instantiate this object
61         """
62         raise NotImplementedError("Singleton is an ABC")
63