Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Java Design Pattern: Singleton Pattern #124

Open
FredWe opened this issue Feb 28, 2017 · 0 comments
Open

Java Design Pattern: Singleton Pattern #124

FredWe opened this issue Feb 28, 2017 · 0 comments

Comments

@FredWe
Copy link
Owner

FredWe commented Feb 28, 2017

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

@FredWe FredWe changed the title Java Design Pattern: Singleton Pattern Java Design Pattern: Singleton Pattern Implementation Feb 28, 2017
@FredWe FredWe changed the title Java Design Pattern: Singleton Pattern Implementation Java Design Pattern: Singleton Pattern Feb 28, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant