Skip to content

Design Patterns

Singleton

Creating the instance and getting it both take O(1) time — that means a constant amount of time, no matter how big your app grows. The real cost here is design, not speed.

The idea, in plain English

A singleton makes sure your app has only ONE of something. Think of a country with only one official government. No matter who you ask, you get the same one. This is handy for shared settings or one shared database connection.

How it works

  1. 1The first time you create it, you build and store the one instance.
  2. 2Every later request gets that same stored instance. It never makes a new one.
  3. 3So everyone shares the exact same object and the exact same data.

When you'd use it

Use this for app-wide settings, a logger, or one shared connection. Use it anywhere a second copy would cause confusion or waste.

Common beginner mistakes

  • Don't overuse it. A global shared object can make your code hard to test and understand.
  • Watch your 'only one' check for bugs. A wrong check can create extra copies by accident.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Same object? yes
b.theme: dark

Not sure this is the right topic? See the learning paths → or where this leads →