DEV Community

Tin Trinh
Tin Trinh

Posted on

Effective Java Part3 - Singleton

Singleton in Java is a concept that describes that a class should have one and only one of the instantiated object. What does that mean? With one class there is no different object initiated.

There is some way to implement that.
First, we can use the static public instance filed in class.
For example

class A {
    public static final A INSTANCE = new A();
    private A() {}
}

With the static final filed, we make a very clear statement about the class

The second way to implement a Singleton is by using the static factory method.

class A {
    private static A INSTANCE = new A();
    public static A getInstance() {
        return INSTANCE;
    }
    private A() {}
}

By using this static factory method we could have some advantage over using the public static instance field.
We could change not using Singleton anymore without changing the API of the class. We could also return the class that is a subtype of the return class.

Top comments (0)