| 1 | // | 
|---|
| 2 | // SingletonHolder.h | 
|---|
| 3 | // | 
|---|
| 4 | // Library: Foundation | 
|---|
| 5 | // Package: Core | 
|---|
| 6 | // Module:  SingletonHolder | 
|---|
| 7 | // | 
|---|
| 8 | // Definition of the SingletonHolder template. | 
|---|
| 9 | // | 
|---|
| 10 | // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. | 
|---|
| 11 | // and Contributors. | 
|---|
| 12 | // | 
|---|
| 13 | // SPDX-License-Identifier:	BSL-1.0 | 
|---|
| 14 | // | 
|---|
| 15 |  | 
|---|
| 16 |  | 
|---|
| 17 | #ifndef Foundation_SingletonHolder_INCLUDED | 
|---|
| 18 | #define Foundation_SingletonHolder_INCLUDED | 
|---|
| 19 |  | 
|---|
| 20 |  | 
|---|
| 21 | #include "Poco/Foundation.h" | 
|---|
| 22 | #include "Poco/Mutex.h" | 
|---|
| 23 |  | 
|---|
| 24 |  | 
|---|
| 25 | namespace Poco { | 
|---|
| 26 |  | 
|---|
| 27 |  | 
|---|
| 28 | template <class S> | 
|---|
| 29 | class SingletonHolder | 
|---|
| 30 | /// This is a helper template class for managing | 
|---|
| 31 | /// singleton objects allocated on the heap. | 
|---|
| 32 | /// The class ensures proper deletion (including | 
|---|
| 33 | /// calling of the destructor) of singleton objects | 
|---|
| 34 | /// when the application that created them terminates. | 
|---|
| 35 | { | 
|---|
| 36 | public: | 
|---|
| 37 | SingletonHolder(): | 
|---|
| 38 | _pS(0) | 
|---|
| 39 | /// Creates the SingletonHolder. | 
|---|
| 40 | { | 
|---|
| 41 | } | 
|---|
| 42 |  | 
|---|
| 43 | ~SingletonHolder() | 
|---|
| 44 | /// Destroys the SingletonHolder and the singleton | 
|---|
| 45 | /// object that it holds. | 
|---|
| 46 | { | 
|---|
| 47 | delete _pS; | 
|---|
| 48 | } | 
|---|
| 49 |  | 
|---|
| 50 | S* get() | 
|---|
| 51 | /// Returns a pointer to the singleton object | 
|---|
| 52 | /// hold by the SingletonHolder. The first call | 
|---|
| 53 | /// to get will create the singleton. | 
|---|
| 54 | { | 
|---|
| 55 | FastMutex::ScopedLock lock(_m); | 
|---|
| 56 | if (!_pS) _pS = new S; | 
|---|
| 57 | return _pS; | 
|---|
| 58 | } | 
|---|
| 59 |  | 
|---|
| 60 | void reset() | 
|---|
| 61 | /// Deletes the singleton object. | 
|---|
| 62 | { | 
|---|
| 63 | FastMutex::ScopedLock lock(_m); | 
|---|
| 64 | delete _pS; | 
|---|
| 65 | _pS = 0; | 
|---|
| 66 | } | 
|---|
| 67 |  | 
|---|
| 68 | private: | 
|---|
| 69 | S* _pS; | 
|---|
| 70 | FastMutex _m; | 
|---|
| 71 | }; | 
|---|
| 72 |  | 
|---|
| 73 |  | 
|---|
| 74 | } // namespace Poco | 
|---|
| 75 |  | 
|---|
| 76 |  | 
|---|
| 77 | #endif // Foundation_SingletonHolder_INCLUDED | 
|---|
| 78 |  | 
|---|