3 Useful Singleton Pattern in Java_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 3 Useful Singleton Pattern in Java

3 Useful Singleton Pattern in Java

 2014/5/3 21:13:45  futeng  程序员俱乐部  我要评论(0)
  • 摘要:1.Eagerinitialization(thread-safe)/***Singletonpatternexamplewitheagerinitializationway.*@author<ahref="mailto:ifuteng@gmail.com">futeng</a>*/publicclassEagerInitSingletion
  • 标签:Java

1. Eager initialization (thread-safe)

?

class="java">/**
* Singleton pattern example with eager initialization way.
* @author <a href="mailto:ifuteng@gmail.com">futeng</a>
*/
public class EagerInitSingletion {

    private static final EagerInitSingletion INSTANCE = new EagerInitSingletion();

    private EagerInitSingletion() {}

    public static EagerInitSingletion getInstance() {
        return INSTANCE;
    }
}

?

2. Double-checked locking (lazy initialization, thread-safe)

/**
* Singleton pattern example with double-checked locking
* @author <a href="mailto:ifuteng@gmail.com">futeng</a>
*/
public class DoubleCheckedSingleton {

    private static volatile DoubleCheckedSingleton INSTANCE = null;

    private DoubleCheckedSingleton() {};

    // Double-checked locking
    public static DoubleCheckedSingleton getInstance() {
        if(INSTANCE == null) {
            synchronized (DoubleCheckedSingleton.class) {
                if(INSTANCE == null) {
                    INSTANCE = new DoubleCheckedSingleton();
                }
            }
        }
        return INSTANCE;
    }
}
?

?

3. Enum way (lazy initialization, thread-safe)

What is the best way to implements a Singleton pattern in Java??Enum way

?

simplest?

public enum EnumWaySingleton {
       INSTANCE;
   }

?more complex

/**
* Singleton Pattern using Java ENUM
* @author <a href="mailto:ifuteng@gmail.com">futeng</a>
*/
public enum EnumWaySingleton {
    INSTANCE;

    private final String[] names = {"xiaoqi", "xiaodi"};

    public void printNames() {
        System.out.println(Arrays.toString(names));
    }

    public static void main(String[] args) {
        EnumWaySingleton.INSTANCE.printNames();
    }
}

?

?

?

?

?

?

?

?

?

?

?
上一篇: 中国一家比特币交易平台宣布停运 下一篇: 没有下一篇了!
发表评论
用户名: 匿名