Skip to content

Java Design Pattern: Singleton Pattern #124

@FredWe

Description

@FredWe

Features (wiki):

An implementation of the singleton pattern must:

  • ensure that only one instance of the singleton class ever exists;
  • and provide global access to that instance.

Typically, this is done by:

  • declaring all constructors of the class to be private;
  • and providing a static method that returns a reference to the instance.

The instance is usually stored as a private static variable; the instance is created when the variable is initialized, at some point before the static method is first called.

(Almost) Best Practices:

1. private static internal holder:

public class Singleton {
    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }
    private Singleton (){}
    public static final Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

The intuitive implementation has thread safety problems (wrong examples, see ref.) This implementation using JVM mechanism itself guarantee the thread safety issue:

  • SingletonHolder is private, there is no access except getInstance(), therefore it's lazy initialization;
  • Meanwhile no synchronizing when reading the instance, prevent from a poor performance;
  • No depandance to any specific JDK version.

2. enum typed class

public enum Singleton{
   INSTANCE;
}

A real elegant implementation. Access from EasySingleton.INSTANCE, easier than calling getInstance() as above.

Creating a enum instance is thread-safe by default, so no thread safety issue. But thread safety of any other method is responsible to programmer himself.

还有防止上面的通过反射机制调用私用构造器。

Ref.: http://coolshell.cn/articles/265.html

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions