How do you build a Singleton in Dart?

2020-01-24 03:19发布

The singleton pattern ensures only one instance of a class is ever created. How do I build this in Dart?

14条回答
小情绪 Triste *
2楼-- · 2020-01-24 03:47

Singleton that can't changed the object after instance

class User {
  final int age;
  final String name;

  User({
    this.name,
    this.age
    });

  static User _instance;

  static User getInstance({name, age}) {
     if(_instance == null) {
       _instance = User(name: name, idade: age);
       return _instance;
     }
    return _instance;
  }
}

  print(User.getInstance(name: "baidu", age: 24).age); //24

  print(User.getInstance(name: "baidu 2").name); // is not changed //baidu

  print(User.getInstance()); // {name: "baidu": age 24}
查看更多
一夜七次
3楼-- · 2020-01-24 03:50

As I'm not very fond of using the new keyword or other constructor like calls on singletons, I would prefer to use a static getter called inst for example:

// the singleton class
class Dao {
    // singleton boilerplate
        Dao._internal() {}
        static final Dao _singleton = new Dao._internal();
        static get inst => _singleton;

    // business logic
        void greet() => print("Hello from singleton");
}

example usage:

Dao.inst.greet();       // call a method

// Dao x = new Dao();   // compiler error: Method not found: 'Dao'

// verify that there only exists one and only one instance
assert(identical(Dao.inst, Dao.inst));
查看更多
甜甜的少女心
4楼-- · 2020-01-24 03:52

Here is another possible way:

void main() {
  var s1 = Singleton.instance;
  s1.somedata = 123;
  var s2 = Singleton.instance;
  print(s2.somedata); // 123
  print(identical(s1, s2));  // true
  print(s1 == s2); // true
  //var s3 = new Singleton(); //produces a warning re missing default constructor and breaks on execution
}

class Singleton {
  static final Singleton _singleton = new Singleton._internal();
  Singleton._internal();
  static Singleton get instance => _singleton;
  var somedata;
}
查看更多
beautiful°
5楼-- · 2020-01-24 03:52

Modified @Seth Ladd answer for who's prefer Swift style of singleton like .shared:

class Auth {
  // singleton
  static final Auth _singleton = Auth._internal();
  factory Auth() => _singleton;
  Auth._internal();
  static Auth get shared => _singleton;

  // variables
  String username;
  String password;
}

Sample:

Auth.shared.username = 'abc';
查看更多
乱世女痞
6楼-- · 2020-01-24 03:56

Dart singleton by const constructor & factory

class Singleton {
  factory Singleton() =>
    const Singleton._internal_();
  const Singleton._internal_();
}


void main() {
  print(new Singleton() == new Singleton());
  print(identical(new Singleton() , new Singleton()));
}
查看更多
混吃等死
7楼-- · 2020-01-24 03:57

I don't find it very intuitive reading new Singleton(). You have to read the docs to know that new isn't actually creating a new instance, as it normally would.

Here's another way to do singletons (Basically what Andrew said above).

lib/thing.dart

library thing;

final Thing thing = new Thing._private();

class Thing {
   Thing._private() { print('#2'); }
   foo() {
     print('#3');
   }
}

main.dart

import 'package:thing/thing.dart';

main() {
  print('#1');
  thing.foo();
}

Note that the singleton doesn't get created until the first time the getter is called due to Dart's lazy initialization.

If you prefer you can also implement singletons as static getter on the singleton class. i.e. Thing.singleton, instead of a top level getter.

Also read Bob Nystrom's take on singletons from his Game programming patterns book.

查看更多
登录 后发表回答