Singleton Pattern
Part of TutorialDesignPatterns
Description
Examples of implementing the Gang of Four Singleton Pattern in D. A Singleton is a class guaranteed to have only a single instance, with a single global access point to that instance.
For the sake of brevity, this tutorial does not cover subclassing of Singletons.
Example 1: Simple Singleton
class Singleton { public static Singleton instance () { if (_instance is null) _instance = new Singleton; return _instance; } protected this () { } private static Singleton _instance; } void main () { auto var = Singleton.instance; }
Example 2: Using Interfaces and Mixins
/* This is the basic interface of a Singleton. */ interface ISingleton { public static ISingleton instance (); } /* This is the mixin for a quick basic implementation of a Singleton. * Note the use of a static variable local to the method, and the special 'typeof(this)' * type expression which allows the mixin to work without knowing the class using it. */ template MSingleton () { public static typeof(this) instance () { static typeof(this) _instance; if (_instance is null) _instance = new typeof(this); return _instance; } } /* This class implements the pattern using the mixin. * Note that using this style, class designers are still on their honor to * make their constructor protected. */ class Foo : ISingleton { mixin MSingleton; protected this () { } } /* This class implements the pattern manually. * Note this is really no different from Example 1, except for the interface. */ class Bar : ISingleton { public static Bar instance () { if (_instance is null) _instance = new Bar; return _instance; } protected this () { } private static Bar _instance; } /* Now let's access our Singletons. */ void main () { auto foo = Foo.instance; auto bar = Bar.instance; }