CTK  0.1.0
The Common Toolkit is a community effort to provide support code for medical image analysis, surgical navigation, and related projects.
ctkSingleton.h
Go to the documentation of this file.
1 /*=========================================================================
2 
3  Library: CTK
4 
5  Copyright (c) Kitware Inc.
6 
7  Licensed under the Apache License, Version 2.0 (the "License");
8  you may not use this file except in compliance with the License.
9  You may obtain a copy of the License at
10 
11  http://www.apache.org/licenses/LICENSE-2.0.txt
12 
13  Unless required by applicable law or agreed to in writing, software
14  distributed under the License is distributed on an "AS IS" BASIS,
15  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  See the License for the specific language governing permissions and
17  limitations under the License.
18 
19 =========================================================================*/
20 
21 
22 #ifndef __ctkSingleton_h
23 #define __ctkSingleton_h
24 
25 //
29 //
32 //
34 //
35 
36 //-----------------------------------------------------------------------------
38 #define CTK_SINGLETON_DECLARE(NAME) \
39 static NAME* Instance; \
40 static void classInitialize(); \
41 static void classFinalize(); \
42 friend class NAME##Initialize; \
43 typedef NAME Self;
44 
45 //-----------------------------------------------------------------------------
48 //
50 //
54 #define CTK_SINGLETON_DECLARE_INITIALIZER(EXPORT_DIRECTIVE,NAME) \
55 class EXPORT_DIRECTIVE NAME##Initialize \
56 { \
57 public: \
58  typedef NAME##Initialize Self; \
59  \
60  NAME##Initialize(); \
61  ~NAME##Initialize(); \
62 private: \
63  static unsigned int Count; \
64 }; \
65  \
66 static NAME##Initialize NAME##Initializer;
67 
68 
69 //-----------------------------------------------------------------------------
70 //
72 //
75 //
76 #define CTK_SINGLETON_DEFINE_INITIALIZER(NAME) \
77 NAME##Initialize::NAME##Initialize() \
78 { \
79  if(++Self::Count == 1) \
80  { NAME::classInitialize(); } \
81 } \
82  \
83 NAME##Initialize::~NAME##Initialize() \
84 { \
85  if(--Self::Count == 0) \
86  { NAME::classFinalize(); } \
87 } \
88  \
89 unsigned int NAME##Initialize::Count; \
90 NAME* NAME::Instance;
91 
92 
93 //----------------------------------------------------------------------------
94 //
96 //
97 #define CTK_SINGLETON_DEFINE(NAME) \
98 void NAME::classInitialize() \
99 { \
100  Self::Instance = new NAME; \
101 } \
102  \
103 void NAME::classFinalize() \
104 { \
105  delete Self::Instance; \
106 } \
107  \
108 CTK_SINGLETON_DEFINE_INITIALIZER(NAME)
109 
111 
112 #endif //__ctkSingleton_h