使用ACE的Singleton(单体)设计模式的简捷方式
Singleton设计模式最简单,也用得常见, 下面是经典的使用示例:* Here is an example:
* @verbatim
* class foo
* {
* friend class ACE_Singleton<foo, ACE_Null_Mutex>;
* private:
* foo () { cout << "foo constructed" << endl; }
* ~foo () { cout << "foo destroyed" << endl; }
* };
* typedef ACE_Singleton<foo, ACE_Null_Mutex> FOO;
* @endverbatim
*
其实,还有一种更简单的方式,在JAWS3中用得更常见
下面是其中一例:
class JAWS_Export JAWS_Concurrency
: public JAWS_Concurrency_Bridge<JAWS_CONCURRENCY_CONCRETE_IMPL>
{
public:
static JAWS_Concurrency * instance (void)
{
return ACE_Singleton<JAWS_Concurrency, ACE_SYNCH_MUTEX>::instance ();
}
};
不错,但不知道有没有测试在不同dll中这个单体是否能正常工作呢?
我的意思是,在a.DLL中做了一个单体类A,
然后在b.dll和c.dll中使用这个单体类,然后在同一进程内调用b.dll和c.dll,
A这个单体是只有一个实例吗?
我以前一直用的楼主的第一种使用方式来做单体,但发现在我说的情况下,不能保证A只有一个实例! Q: How do I instantiate a singleton from a DLL?A: Singletons in DLLs on Windows
If you want to instantiate a singleton in a DLL on Windows, follow these steps: [*]Use generate_export_file.pl (found in ACE_wrappers/bin) to generate the proper Win32 export directives for your dll. For example, "perl generate_export_file.pl MyLib >MyLib_Export.h" generates the following output in the file "MyLib_Export.h": // -*- C++ -*-
// generate_export_file.pl,v 1.8 2001/03/04 09:16:29 nanbor Exp
// Definition for Win32 Export directives.
// This file is generated automatically by generate_export_file.pl
// ------------------------------
#ifndef MYLIB_EXPORT_H
#define MYLIB_EXPORT_H
#include "ace/config-all.h"
#if !defined (MYLIB_HAS_DLL)
#define MYLIB_HAS_DLL 1
#endif /* ! MYLIB_HAS_DLL */
#if defined (MYLIB_HAS_DLL) && (MYLIB_HAS_DLL == 1)
#if defined (MYLIB_BUILD_DLL)
# define MyLib_Export ACE_Proper_Export_Flag
# define MYLIB_SINGLETON_DECLARATION(T) ACE_EXPORT_SINGLETON_DECLARATION (T)
# define MYLIB_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) ACE_EXPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK)
#else /* MYLIB_BUILD_DLL */
# define MyLib_Export ACE_Proper_Import_Flag
# define MYLIB_SINGLETON_DECLARATION(T) ACE_IMPORT_SINGLETON_DECLARATION (T)
# define MYLIB_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK) ACE_IMPORT_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK)
#endif /* MYLIB_BUILD_DLL */
#else /* MYLIB_HAS_DLL == 1 */
#define MyLib_Export
#define MYLIB_SINGLETON_DECLARATION(T)
#define MYLIB_SINGLETON_DECLARE(SINGLETON_TYPE, CLASS, LOCK)
#endif /* MYLIB_HAS_DLL == 1 */
#endif /* MYLIB_EXPORT_H */
// End of auto generated file.[*]When declaring your singleton, make sure and use the right export directive that you generated for your dll. For instance, if you create a class that is meant to be a singleton in MyLib.dll, you'd typically do this: class MyLib_Export MyClass
{
};
typedef ACE_Singleton<MyClass, ACE_Null_Mutex> MY_CLASS_SINGLETON;
MYLIB_SINGLETON_DECLARE(ACE_Singleton, MyClass, ACE_Null_Mutex);
[ 本帖最后由 peakzhang 于 2008-1-15 21:26 编辑 ]
页:
[1]