enum singleton

来源:互联网 发布:双肩电脑包 知乎 编辑:程序博客网 时间:2024/04/30 13:46

原文:http://en.wikipedia.org/wiki/Singleton_pattern#The_Enum-way


In the second edition of his book Effective JavaJoshua Bloch claims that "a single-element enum type is the best way to implement a singleton" for any Java that supports enums. The use of an enum is very easy to implement and has no drawbacks regarding serializable objects, which have to be circumvented in the other ways.

public enum Singleton {        INSTANCE;        public void execute (String arg) {                //... perform operation here ...        }}

The public method can be written to take any desired types of arguments; a single String argument is used here as an example.

This approach implements the singleton by taking advantage of Java's guarantee that any enum value is instantiated only once in a Java program. Since Java enum values are globally accessible, so is the singleton. The drawback is that the enum type is somewhat inflexible; for example, it does not allow lazy initialization.

原创粉丝点击