What is the best way to implement singletons in Haxe? I can make a class and pass it between subclasses etc but I do not want to do that is possible. I am looking for a simpler way to do that as the singleton pattern supposed to keep things simple. It would be nice all instanced classes can access this data without passing them around to keep it simple.
class someClass {
// You refer to "someClass.instance.<<whatever>>"
static public var instance(get_instance, never) : someClass;
//
// This is the "secret stash" that holds the instance itself.
static private var _INSTANCE : someClass;
//
// ... and here's the code that does the magic:
static public function get_instance():AwayStats {
return (_INSTANCE != null) ?
_INSTANCE :
_INSTANCE = new someClass();
}
...
}
The various modules in your application simply refer to “someClass.instance.whatever”
Because both the getter-function and the corresponding (private …) variable have been defined to be “static,” they belong to the class, not to any particular object-instance. The first caller causes the object to be instantiated. All subsequent calls return the same object. (Note that this technique is, at least theoretically, “not thread-safe,” since … in your computer-science class, at least … a race could occur to instantiate the variable.)
class MySingleton {
static public var instance(get, null):MySingleton;
static function get_instance(): MySingleton return (instance == null) ? instance = new MySingleton() : instance;
// ...
private function new() {}
}
For the record, player_03’s version is equivalent to mine, only slightly more verbose…
It will now define a constructor if you haven’t defined one yourself. (Which you’ll have to do if you need to supply arguments to the superclass constructor.)
In the haxelib version, Singleton is a class, and you can only extend one class at a time. If you want a singleton of a display object, you’re out of luck.
In my version, it’s an interface, so it doesn’t get in the way. (You can implement as many interfaces as you want.)
Also, my version requires slightly less code - you only have to type ClassName.instance, rather than ClassName.getInstance().
No, not yet. I submitted a pull request, but it’s up to DelishusCake to accept it. I guess I could submit it under a different name, but that’s far from ideal.