Initial commit
[ta/config-manager.git] / cmframework / src / cmframework / server / cmsingleton.py
1 # Copyright 2019 Nokia
2
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15
16 class _CMSingleton(type):
17     _instances = {}
18
19     def __call__(cls, *args, **kwargs):
20         if cls not in cls._instances:
21             cls._instances[cls] = super(_CMSingleton, cls).__call__(*args, **kwargs)
22         return cls._instances[cls]
23
24
25 class CMSingleton(_CMSingleton('SingletonMeta', (object,), {})):
26     pass
27
28
29 def main():
30     class TestSingleton(CMSingleton):
31         def __init__(self):
32             self.counter = 0
33
34         def inc(self):
35             self.counter += 1
36
37         def dec(self):
38             self.counter -= 1
39
40         def __str__(self):
41             return 'Counter now is %d' % self.counter
42
43     instance1 = TestSingleton()
44     instance1.inc()
45     instance2 = TestSingleton()
46     instance2.inc()
47     print str(instance2)
48
49
50 if __name__ == '__main__':
51     main()