`
futeng
  • 浏览: 263784 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

3 Useful Singleton Pattern in Java

阅读更多

1. Eager initialization (thread-safe)

 

/**
* 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();
    }
}

 

 

 

 

 

 

 

 

 

 

 
1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics