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?
Imho it looks fine.
For creation get() should be always used, since it is the most
convenient way to ensure that there is really only one instance
of the singleton. Just make this() private, so only you can
create new instances:
private this()
{
}
And you probably don't need instantiated_, you can always check
whether instance_ is null or not. So:
if (instance_ is null)
{
...
}
else
{
...
}