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


当前回答

你可以只使用Constant构造函数。

class Singleton {
  const Singleton(); //Constant constructor
  
  void hello() { print('Hello world'); }
}

例子:

Singleton s = const Singleton();
s.hello(); //Hello world

根据文件:

恒定的构造函数 如果类生成永不更改的对象,则可以使这些对象成为编译时常量。为此,定义一个const构造函数,并确保所有实例变量都是final变量。

其他回答

我觉得阅读new Singleton()不是很直观。你必须阅读文档才能知道new实际上并没有像通常那样创建一个新实例。

这里有另一种方法来做单例(基本上是Andrew上面说的)。

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();
}

注意,由于Dart的惰性初始化,直到第一次调用getter时才创建单例。

如果你愿意,你也可以在单例类上作为静态getter来实现单例。即的事情。单例,而不是顶级getter。

还可以阅读Bob Nystrom在他的游戏编程模式书中对单身人士的看法。

你可以只使用Constant构造函数。

class Singleton {
  const Singleton(); //Constant constructor
  
  void hello() { print('Hello world'); }
}

例子:

Singleton s = const Singleton();
s.hello(); //Hello world

根据文件:

恒定的构造函数 如果类生成永不更改的对象,则可以使这些对象成为编译时常量。为此,定义一个const构造函数,并确保所有实例变量都是final变量。

在这个例子中,当我想要使用Singleton时,我做了其他必要的事情。例如:

将一个值传递给单例对象的构造函数 在构造函数内部初始化一个值 为Singleton的变量设置一个值 能够访问和访问这些值。

是这样的:

class MySingleton {

  static final MySingleton _singleton = MySingleton._internal();

  String _valueToBeSet;
  String _valueAlreadyInSingleton;
  String _passedValueInContructor;

  get getValueToBeSet => _valueToBeSet;

  get getValueAlreadyInSingleton => _valueAlreadyInSingleton;

  get getPassedValueInConstructor => _passedValueInContructor;

  void setValue(newValue) {
    _valueToBeSet = newValue;
  }

  factory MySingleton(String passedString) {
    _singleton._valueAlreadyInSingleton = "foo";
    _singleton._passedValueInContructor = passedString;

    return _singleton;
  }

  MySingleton._internal();
}

MySingleton的用法:

void main() {

MySingleton mySingleton =  MySingleton("passedString");
mySingleton.setValue("setValue");
print(mySingleton.getPassedValueInConstructor);
print(mySingleton.getValueToBeSet);
print(mySingleton.getValueAlreadyInSingleton);

}

因为我不太喜欢使用new关键字或其他构造函数,比如对单例对象的调用,我更喜欢使用一个名为inst的静态getter:

// 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");
}

使用示例:

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));

在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实例。