2021年3月28日星期日

Why is the singleton pattern never shown as a class with const constructor?

It is a pattern which makes sure we create only one instance of the class.

Most of the time singleton pattern is shown:

 class Settings {        static final Settings _instance = Settings._internal();        factory Settings() {          return _instance;        }        Settings._internal() {}      }  

disadvantages: difficult to test and violates single responsibility

What about:

class Singleton{     const Singleton();  }      Singleton s1=  const Singleton();  Singleton s2=  const Singleton();      void main() {      print(s1==s2); //true  }  

Easy to test. Only one 1 responsibility of the object.

My question is why people make life more difficult and never implement Singleton with const constructor. Did I miss anything?

https://stackoverflow.com/questions/66848076/why-is-the-singleton-pattern-never-shown-as-a-class-with-const-constructor March 29, 2021 at 10:28AM

没有评论:

发表评论