0

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?

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393

1 Answers1

1

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.

hacker1024
  • 3,186
  • 1
  • 11
  • 31
  • I'm accepting your answer for now, but it's interesting to note that the [language specs](https://github.com/dart-lang/language/blob/master/accepted/future-releases/enhanced-enums/feature-specification.md#singleton) mention that people might use enums as singletons. – Suragch Jun 29 '22 at 16:46
  • You can use enums for *constant* singletons. There are classes with no mutable state, often even no state at all, that you only ever need one instance of (because, why have two if they have the same state anyway). Enums work for that. For singletons with dynamically allocated state, you can't use enums. (It's not a good pattern anyway, I'd prefer a "zone-local value" instead of a source-enforced singleton.) – lrn Jun 30 '22 at 09:27