在Dart中,是否可以单例传递参数?

时间:2019-05-11 08:45:38

标签: oop dart flutter singleton

class Peoples {
  int id;
  String name;

  static final Peoples _inst = Peoples._internal();

  Peoples._internal();

  factory Peoples() {
    return _inst;
  }
}

我有这个单例课程。这样可以确保只创建一个类的实例。因此,即使有人尝试实例化它,他们也将使用相同的实例。我可以创建和设置值,例如:

  Peoples ps1 = Peoples();
  Peoples ps2 = Peoples();

  ps1.id = 1;
  ps1.name = "First";

  ps2.id = 2;
  ps2.name = "Second";

是否可以实例化和设置以下值:

  Peoples ps1 = Peoples(1, "First");
  Peoples ps2 = Peoples(2, "Second");

因此,现在“ ps1”和“ ps2”都将具有(2,“ Second”)。

2 个答案:

答案 0 :(得分:2)

当然! 您需要将参数传递给factory方法,然后需要使用引用的实例来更新属性。

例如,您拥有

class Peoples {
  int id;
  String name;

  static final Peoples _inst = Peoples._internal();

  Peoples._internal();

  factory Peoples() {
    return _inst;
  }
}

如果您应用我的解决方案,那么您有

class Peoples {
  int id;
  String name;

  static final Peoples _inst = Peoples._internal();

  Peoples._internal();

  factory Peoples({int id, String name}) {
    _inst.id = id
    _inst.name = name
    return _inst;
  }
}

对此您的问题应予以回答 有关工厂和参数的更多信息,请访问

https://dart.dev/guides/language/language-tour

工作示例

class Peoples {
  int id;
  String name;

  static final Peoples _inst = Peoples._internal();

  Peoples._internal();


  factory Peoples(int id, String name) {
    _inst.id = id;
    _inst.name = name;
    return _inst;
  }
}

void main() {
  print("Instance of = " + Peoples(0, "Dylan").name);
  print("Instance of = " + Peoples(1, "Joe").name);
  print("Instance of = " + Peoples(2, "Maria").name);
}

答案 1 :(得分:2)

我想回答显示一种通过向其传递参数来创建单例的方法,以及如何在首次创建后“锁定”其值。

class People {
  static final People _inst = People._internal();
  People._internal();

  factory People(int id, String name) {
    assert(!_inst._lock, "it's a singleton that can't re-defined");
    _inst.id = id;
    _inst.name = name;
    _inst._lock = true;
    return _inst;
  }
  
  int id;
  String name;
  bool _lock = false;
}

void main() {
  var people = People(0, 'Dylan');
  try{
    print('Instance of = ' + People(0, 'Joe').name);
    print('Instance of = ' + People(1, 'Maria').name);
    print('Instance of = ' + People(2, 'Ete sech').name);
  } finally {
    print('Instance of = ' + people.name);
  }
}