Skip to content

Instantly share code, notes, and snippets.

@theburningmonk
Last active September 2, 2022 01:40
Show Gist options
  • Save theburningmonk/6401183 to your computer and use it in GitHub Desktop.
Save theburningmonk/6401183 to your computer and use it in GitHub Desktop.
Using Dart's factory constructor feature to implement the singleton pattern
class MyClass {
static final MyClass _singleton = new MyClass._internal();
factory MyClass() {
return _singleton;
}
MyClass._internal() {
... // initialization logic here
}
... // rest of the class
}
// consuming code
MyClass myObj = new MyClass(); // get back the singleton
...
// another piece of consuming code
MyClass myObj = new MyClass(); // still getting back the singleton
@icnahom
Copy link

icnahom commented Oct 5, 2021

Singleton design pattern is intended to create one and only one (single) instance of a class.

If you wanted a single instance with a parameter, how would you do that?

Do you see any issue in this code?

class MyClass  {
  MyClass._(this.parameter);
  final String parameter;

  static MyClass? _instance;

  static void initialize(String parameter) {
    _instance = MyClass._(parameter );
  }

  static MyClass get instance => _instance!; // throw an "initialize first" error

  // access parameter 
}

@elbeicktalat
Copy link

Singleton design pattern is intended to create one and only one (single) instance of a class.

If you wanted a single instance with a parameter, how would you do that?

Do you see any issue in this code?
This is not a singleton implementation.

See this for reference: Dart Null-Safty Singleton with parameters

@srihari9n
Copy link

Can MyClass extend an abstract class with non-null constructor? If so how?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment