Home > Back-end >  Singleton pattern in Dart to make to make shared object
Singleton pattern in Dart to make to make shared object

Time:10-14

What does this code do? There is no such function _sharedInstance(), at least I didn't find it. Why the code line LoadingScreen._sharedInstance(); used again to define _shared ? Why to use factory there? I.e. this code seems incomprehensible...

class LoadingScreen {
  LoadingScreen._sharedInstance();
  static final LoadingScreen _shared = LoadingScreen._sharedInstance();
  factory LoadingScreen.instance() => _shared;
  ...

CodePudding user response:

This is a Singleton pattern.

_sharedInstance() is just a private named constructor for LoadingScreen, after defining it the class no longer has a default constructor. You can name it anything and it will be private as long as it starts with _. Check out Named Constructors.

_shared is used to hold the only instance of LoadingScreen, and it gets it's value from invoking the _sharedInstance() private named constructor.

If you call LoadingScreen.instance() in your code, you will always get the same object that is stored in _shared. Check out Factory Constructors.

CodePudding user response:

This is a way to build Singleton. Thanks to Dart's factory constructors, it's easy to build a singleton:

I suggest it needs a couple of points of explanation. There's the weird syntax LoadingScreen. _sharedInstance() that looks like a method call bu actually it's really a constructor definition. There's the _sharedInstance name. And there's the nifty language design point that Dart lets you start out using an ordinary constructor and then if needed, change it to a factory method without changing all the callers.

  • Related