Pattern · Intro

Singleton

Guarantee a class has exactly ONE instance and give the whole program a single point of access to it.

Asked atAmazonMicrosoftAdobe
step 1 / 8
1/2One instance, ever
Config
- instance: Config «static»
- Config()
+ getInstance(): Config «static»
One instance, ever
1class Config {
2 private static Config instance;
3 private Config() { } // constructor is private
4 static Config getInstance() {
5 if (instance == null)
6 instance = new Config(); // created once, lazily
7 return instance;
8 }
9}
State
constructorprivate

The constructor is PRIVATE — no other code can write `new Config()`. That's how the class controls its own instantiation.