Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members | Related Pages

singleton.h

Go to the documentation of this file.
00001 /*
00002    Copyright (C) 2002 Simon Hausmann <simon@lst.de>
00003 
00004    This library is free software; you can redistribute it and/or
00005    modify it under the terms of the GNU Library General Public
00006    License as published by the Free Software Foundation; either
00007    version 2 of the License, or (at your option) any later version.
00008 
00009    This library is distributed in the hope that it will be useful,
00010    but WITHOUT ANY WARRANTY; without even the implied warranty of
00011    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00012    Library General Public License for more details.
00013 
00014    You should have received a copy of the GNU Library General Public License
00015    along with this library; see the file COPYING.LIB.  If not, write to
00016    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
00017    Boston, MA 02111-1307, USA.
00018 */
00019 
00020 #ifndef SINGLETON_H
00021 #define SINGLETON_H
00022 
00023 #include "threadutil.h"
00024 
00025 template <class Product>
00026 struct DefaultSingletonCreator
00027 {
00028     static Product *create() { return new Product; }
00029 };
00030 
00031 template <class Product>
00032 struct NullSingletonCreator
00033 {
00034     static Product *create() { return 0; }
00035 };
00036 
00037 template 
00038 <
00039     class T,
00040     template <class> class Creator = DefaultSingletonCreator
00041 >
00042 class Singleton
00043 {
00044 public:
00045     static T &self()
00046     {
00047         if ( !s_self ) {
00048             ThreadUtil::AutoLock lock( s_guard );
00049             if ( !s_self )
00050                 s_self = Creator<T>::create();
00051         }
00052         return *s_self;
00053     }
00054 
00055 protected:
00056     Singleton()
00057     { s_self = static_cast<T *>( this ); }
00058     ~Singleton()
00059     { s_self = 0; }
00060 
00061 private:
00062     Singleton( const Singleton<T, Creator> &rhs );
00063     Singleton<T, Creator> &operator=( const Singleton<T, Creator> &rhs );
00064 
00065     static T *s_self;
00066     static ThreadUtil::Mutex s_guard;
00067 };
00068 
00069 template <class T, template <class> class Creator>
00070 T *Singleton<T, Creator>::s_self = 0;
00071 
00072 template <class T, template <class> class Creator>
00073 ThreadUtil::Mutex Singleton<T, Creator>::s_guard;
00074 
00075 #endif // SINGLETON_H
00076 /* vim: et sw=4 ts=4
00077  */

Generated on Sat Nov 5 16:17:33 2005 for OPIE by  doxygen 1.4.2