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