Michael Vo
vo.dev

Follow

vo.dev

Follow

Singletons

Michael Vo's photo
Michael Vo
·Nov 12, 2022·

1 min read

Singleton Pattern is used in object-oriented programming to ensure that a class has only one instance. Example of using single in Dart

void main() {
  print(FileSystemManager().hashCode == FileSystemManager().hashCode);
  print('HashCode for class is ${FileSystemManager().hashCode}');
}

class FileSystemManager {
  static final FileSystemManager _instance = FileSystemManager._internal();

  factory FileSystemManager() {
    return _instance;
  }
  FileSystemManager._internal() {
    //initialization logic
  }

  void openFile() {}
  void writeFile() {}

}

DartPad

 
Share this