Building a singleton

In some cases, you only need one unique instance of a class because this is simply enough for the app you're working with, or perhaps to save resources. This recipe shows you how to do this in Dart.

How to do it...

The singleton example shows how to do this (substitute your singleton class name for Immortal). Use a factory constructor to implement the singleton pattern, as shown in the following code:

class Immortal {
  static final Immortal theOne = new Immortal._internal('Connor MacLeod'),
  String name;
  factory Immortal(name) => theOne;
  // private, named constructor
  Immortal._internal(this.name); }

main() {
  var im1 = new Immortal('Juan Ramirez'),
  var im2 = new Immortal('The Kurgan'),
  print(im1.name);               // Connor MacLeod
  print(im2.name);               // Connor MacLeod
  print(Immortal.theOne.name);   // Connor MacLeod
  assert(identical(im1, im2));
}

All Immortal instances are the same object.

How it works...

The Immortal class contains an object of its own type, which instantiates itself by calling the private _internal constructor. Because it will be unique, we declare it as static. The factory constructor always returns this instance; only one instance of the Singleton class (named Immortal here) can ever exist in the executing isolate. It has to be a factory constructor because only this type can return a value. The code can even be shortened, shown as follows:

class Singleton {
  factory Singleton() => const Singleton._internal_();
  const Singleton._internal_();
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset