GardenMobile & interfaces

Making a Dart singleton visible at the call site

A small comparison between explicit instance access, ordinary construction, and a factory constructor.

An explicit singleton accessor tells a reader that a call returns a shared object. The original example made that distinction visible:

class SampleSingle {
  SampleSingle._private();
  static final instance = SampleSingle._private();

  // Usage:
  // SampleSingle.instance
}

An ordinary class instead exposes normal construction:

class SampleNormal {
  SampleNormal();

// Usage:
// SampleNormal()
}

A factory can return a shared instance while retaining constructor-like syntax:

class Singleton {
  static final Singleton instance = Singleton._private();
  Singleton._private();
  factory Singleton() => instance;
}

The source preferred the first style because SampleSingle.instance communicates sharing at the call site. That is a readability preference, not a rule that Dart factories cannot implement singletons.

Shared lifetime and mutable state still need a reason. These historical examples have not been compiled for this revision.

← Back to the garden