Home > Enterprise >  Singletons with Dart enums?
Singletons with Dart enums?

Time:06-30

One of the recommended ways of creating singletons in Java is to use an enum.

There are other ways of creating singletons in Dart, but with the new enhanced enums I got to wondering if this could be added to the list.

On a superficial level it seems possible:

enum Singleton {
  instance();

  const Singleton();
}

But would it really work to make a database helper or logger? Since the constructor needs to be constant, I don't think it would work, but am I missing a possible way of doing it?

CodePudding user response:

As enums need a const constructor, they can contain no mutable fields.

Any functions declared inside the enum would need to be free of side-effects, and no more useful than top-level or static functions.

There's not much point to doing this. The Dart guidelines prefer top-level functions over classes containing only static members.

  • Related