Package horizons :: Package util :: Package python :: Module singleton
[hide private]
[frames] | no frames]

Source Code for Module horizons.util.python.singleton

 1  # ################################################### 
 2  # Copyright (C) 2008-2017 The Unknown Horizons Team 
 3  # team@unknown-horizons.org 
 4  # This file is part of Unknown Horizons. 
 5  # 
 6  # Unknown Horizons is free software; you can redistribute it and/or modify 
 7  # it under the terms of the GNU General Public License as published by 
 8  # the Free Software Foundation; either version 2 of the License, or 
 9  # (at your option) any later version. 
10  # 
11  # This program is distributed in the hope that it will be useful, 
12  # but WITHOUT ANY WARRANTY; without even the implied warranty of 
13  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
14  # GNU General Public License for more details. 
15  # 
16  # You should have received a copy of the GNU General Public License 
17  # along with this program; if not, write to the 
18  # Free Software Foundation, Inc., 
19  # 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA 
20  # ################################################### 
21   
22  ''' 
23  Warning: 
24          A Singleton is to some extend the OOP-version of a global variable. 
25          The Singleton pattern has many downsides. 
26          Please make sure that this is really the best solution before using this code! 
27  ''' 
28   
29  from typing import Any, Optional 
30   
31   
32 -class Singleton(type):
33 """Traditional Singleton design pattern. 34 35 USAGE: 36 class MyClass: 37 __metaclass__ = Singleton 38 """
39 - def __init__(self, name, bases, dict):
40 super().__init__(name, bases, dict) 41 self.instance = None # type: Optional[Any]
42
43 - def __call__(self, *args, **kwargs):
44 if self.instance is None: 45 self.instance = super().__call__(*args, **kwargs) 46 return self.instance
47
48 - def destroy_instance(self):
49 self.instance = None
50 51
52 -class ManualConstructionSingleton(Singleton):
53 """Same as Singleton, but Class() never creates an instance. 54 Only create_instance() does."""
55 - def __call__(self):
56 return self.instance
57
58 - def create_instance(self, *args, **kwargs):
59 self.instance = super().__call__(*args, **kwargs)
60