Singleton in Action?

Norm norm.rowtree at gmail.com
Sun Feb 3 02:38:32 UTC 2019


On Saturday, 2 February 2019 at 16:56:45 UTC, Ron Tarrant wrote:
> Hi guys,
>
> I ran into another snag this morning while trying to implement 
> a singleton. I found all kinds of examples of singleton 
> definitions, but nothing about how to put them into practice.
>
> Can someone show me a code example for how one would actually 
> use a singleton pattern in D? When I did the same thing in PHP, 
> it took me forever to wrap my brain around it, so I'm hoping to 
> get there a little faster this time.
>
> Here's the singleton code I've been playing with:
>
> class DSingleton
> {
> 	private:
> 	// Cache instantiation flag in thread-local bool
> 	// Thread local
> 	static bool instantiated_;
>
> 	// Thread global
> 	__gshared DSingleton instance_;
>
> 	this()
> 	{
> 		
> 	} // this()
>
> 	public:
> 	
> 	static DSingleton get()
> 	{
> 		if(!instantiated_)
> 		{
> 			synchronized(DSingleton.classinfo)
> 			{
> 				if(!instance_)
> 				{
> 					instance_ = new DSingleton();
> 					writeln("creating");
> 				}
>
> 				instantiated_ = true;
> 			}
> 		}
> 		else
> 		{
> 			writeln("not created");
> 		}
>
> 		return(instance_);
> 		
> 	} // DSingleton()
>
> } // class DSingleton
>
> So, my big question is, do I instantiate like this:
>
> DSingleton singleton = new DSingleton;
>
> Or like this:
>
> DSingleton singleton = singleton.get();
>
> And subsequent calls would be...? The same? Using get() only?

Sorry, I should read the post fully before replying, my bad. You 
access the singleton via the get() function whenever you need it. 
It is static so there's no need to create a copy of the instance 
in a "singleton" variable.

DSingleton singleton = new DSingleton; is bad. It bypasses all 
the checks in the "get()" method to ensure it is a singleton and 
outside the module where you defined DSingleton it won't compile.

bye,
norm











More information about the Digitalmars-d-learn mailing list