[MUD-Dev] Singleton design pattern (OT?)

Eli Stevens {KiZurich} c718157 at showme.missouri.edu
Tue Aug 31 01:09:44 New Zealand Standard Time 1999


I have been working on the problem of how to best implement the Singleton
class [1] from _Design Patterns_, by Gamma, et al. in C++.  I have wasted a
lot of time fooling around with this, and now that I have an answer that I
think I like, I am going to throw it out in hopes that someone else will be
saved a bit of time.  :)

My goals for implementation are (YMMV):

1. As clean an implementation as possible.
2. As little code as possible in the final, concrete singleton class.
3. The destructor for a singleton class be called, and only if that class
was used during the program (don't make an instance of a class only to
delete it).

Here is what I have so far (and I think I am done):

----------

template <class Singleton> inline Singleton& Inst( void )
{
	static Singleton _inst;

	return _inst;
}

class MyClass
{
protected:
	MyClass();
public:
	template <typename Singleton> friend Singleton& Inst( void );

	void myMemberFn( int var ) {};
}

void main()
{
	Inst<MyClass>().myMemberFn( 17 );
	// at this point, the one instance of MyClass would be created.
	// it will automatically be destroyed.
}

----------

One downside to my approach is that passing in values to the constructor
could get ugly since they would all have to go through the Inst function.
If anyone knows of a good way to do so, or a better way to implement
Singletons in general, I would be very interested in knowing more.

Silence is alone
Eli - mailto:c718157 at showme.missouri.edu

[1] - A class that is insured to only have one instance in a program and
provides a global point of access to that single instance.  Can be used
instead of global varibles to provide more control over the instance.

A basic implementation from _Design Patterns_ (p. 128):

----------

class Singleton
{
public:
	static Singleton* Instance();
protected:
	Singleton();
private
	static Singleton* _instance;
}

Singleton* Singleton::_instance = NULL;

Singleton* Singleton::Instance()
{
	if( _instance == NULL )
		_instance = new Singleton;
	return _instance;
}

----------




_______________________________________________
MUD-Dev maillist  -  MUD-Dev at kanga.nu
http://www.kanga.nu/lists/listinfo/mud-dev



More information about the MUD-Dev mailing list