Sobes.tech
Junior — Middle

Can you give an example of implementing the Singleton pattern in code?

sobes.tech AI

Answer from AI

In Dart (the language used in Flutter), the Singleton pattern can be implemented using a private constructor and a static field that holds the single instance of the class. Here's a simple example:

class Singleton {
  // Private constructor
  Singleton._privateConstructor();

  static final Singleton _instance = Singleton._privateConstructor();

  // Factory constructor returns the single instance
  factory Singleton() {
    return _instance;
  }

  void someMethod() {
    print('Calling Singleton method');
  }
}

void main() {
  var s1 = Singleton();
  var s2 = Singleton();

  print(identical(s1, s2)); // true, both objects are the same
  s1.someMethod();
}

Thus, the Singleton class guarantees that only one instance will be created, and all constructor calls return this same object.