Singleton的实现应该让构造函数成为私有比较好,防止客户程序自己生成对象实例。
下面是我改的方案。
/**
* @(#) Singleton.h
* @author quickpoint At HUST
* @version 1.0 2006-08-21
*/
#ifndef _SINGLETON_H_
#define _SINGLETON_H_
/**
* Singleton is a default implementation of the
* famous pattern: Singleton.
*/
class Singleton {
public:
/**
* The single instance
*/
static Singleton & getInstance( void );
//////////////////////////////////////////////////////////////////
/**
* The methods
*/
void test( void ) const;
private:
// private constructors
Singleton();
Singleton( const Singleton & );
Singleton & operator= ( const Singleton &);
};
#endif /* _SINGLETON_H_ */
/**
* @(#)Singleton.cpp
* @author quickpoint At HUST
* @version 1.0 2006-08-21
*/
#include <iostream>
#include "Singleton.h"
/**
* This is the implementation file
*/
/////////////////////////////////////////////////////////////////////
/**
* Get the only one instance
* @return only one instance
*/
Singleton & Singleton::getInstance( void ) {
static Singleton g_instance; // only one instance
return g_instance;
}
/**
* Private constructor
*/
Singleton::Singleton() {
}
/**
* The test method
*/
void Singleton::test( void ) const {
std::cout << "This is a singleton test." << std::endl;
}
/////////////////////////////////////////////////////////////////////
/**
* A simple test, compile it with:
* g++ -o Singleton -DDEBUG=1 Singleton.cpp
*/
#if DEBUG
using namespace std;
int main( int argc, char * argv[] ) {
Singleton::getInstance().test();
return 0;
}
#endif
回复 更多评论