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.

原文链接:Effective Java Part3 – Singleton

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容