单例模式确保只创建一个类的实例。我如何在达特建立这个?


当前回答

创建单例

class PermissionSettingService {
  static PermissionSettingService _singleton = PermissionSettingService._internal();

  factory PermissionSettingService() {
    return _singleton;
  }

  PermissionSettingService._internal();
}

重置单例

// add this function inside the function
  void reset() {
   _singleton = PermissionSettingService._internal();
  }

其他回答

我在dart和之前的Swift上使用这个简单的模式。我喜欢它的简洁和只有一种使用方式。

class Singleton {
  static Singleton shared = Singleton._init();
  Singleton._init() {
    // init work here
  }

  void doSomething() {
  }
}

Singleton.shared.doSomething();

多亏了Dart的工厂构造函数,构建一个单例对象变得很容易:

class Singleton {
  static final Singleton _singleton = Singleton._internal();

  factory Singleton() {
    return _singleton;
  }

  Singleton._internal();
}

你可以这样构造它

main() {
  var s1 = Singleton();
  var s2 = Singleton();
  print(identical(s1, s2));  // true
  print(s1 == s2);           // true
}

这是我做单例的方式,接受参数(你可以直接粘贴到https://dartpad.dev/):

void main() {
  
  Logger x = Logger('asd');
  Logger y = Logger('xyz');
  
  x.display('Hello');
  y.display('Hello There');
}


class Logger{
  
  
  Logger._(this.message);
  final String message;
  static Logger _instance = Logger._('??!?*');
  factory Logger(String message){
    if(_instance.message=='??!?*'){
      _instance = Logger._(message);
    }
    return _instance;
  }
  
  void display(String prefix){
    print(prefix+' '+message);
  }
  
}

输入:

Hello asd
Hello There asd

“? ? ! ?*'你看到的只是一个工作区,我做了初始化_instance变量暂时没有使它成为一个Logger?类型(空安全)。

在库中使用全局变量怎么样?

single.dart:

library singleton;

var Singleton = new Impl();

class Impl {
  int i;
}

main.dart:

import 'single.dart';

void main() {
  var a = Singleton;
  var b = Singleton;
  a.i = 2;
  print(b.i);
}

或者这是不受欢迎的?

单例模式在Java中是必要的,因为在Java中不存在全局变量的概念,但在Dart中似乎不需要绕这么长的路。

在Dart中创建Singleton没有什么棘手的。您可以在顶级(全局)位置声明任何变量,默认情况下这是一个单例。也可以将变量声明为类的静态成员。这是单元素a。

class A {}

final a = A();

However, the above does not allow you to replace the instance for testing. The other issue is that as the app grows in complexity, you may want to convert global or static variables to transient dependencies inside your classes. If you use dependency injection, you can change a dependency inside your composition at any time. This is an example of using ioc_container to configure a singleton instance of A in the root of an app. You can change this to a transient dependency any time by using add instead of addSingletonService

import 'package:ioc_container/ioc_container.dart';

class A {}

void main(List<String> arguments) {
  final builder = IocContainerBuilder()..addSingletonService(A());
  final container = builder.toContainer();
  final a1 = container<A>();
  final a2 = container<A>();
  print(identical(a1, a2));
}

上面打印为真,因为应用程序只会生成一个A实例。