> For the complete documentation index, see [llms.txt](https://heronyang.gitbook.io/clean-up-your-spaghetti/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://heronyang.gitbook.io/clean-up-your-spaghetti/4_stand_on_giants/singleton_pattern.md).

# Singleton Pattern

## Problem

Exactly one instance of a class is allowed - it is a "singleton." Objects need a global and single point of access.

## Solution

Define a static method of the class that returns the singleton.

```java
public class SingletonDemo {

    private static SingletonDemo instance = null;
    private SingletonDemo() { }

    public static synchronized SingletonDemo getInstance() {

        if (instance == null) {
            instance = new SingletonDemo();
        }

        return instance;
    }

}
```

*This is a lazy initialization.*
