package com.phome.singleton;
/**
* 單例模式的三種實現方式
*/
public class SingletonDemo {
// 方式一:餓漢模式
// private static SingletonDemo singletonDemo = new SingletonDemo();
// private SingletonDemo(){}
// public SingletonDemo getInstance(){
// return singletonDemo;
// }
// 方式二:懶漢模式
// private static SingletonDemo singletonDemo = null;
// private SingletonDemo(){}
// public static SingletonDemo getInstance(){
// if (singletonDemo == null){
// singletonDemo = new SingletonDemo();
// }
// return singletonDemo;
// }
// 方式三:雙重校驗(常用)
// 使用volatile關鍵字是禁止java中的指令重排序優化使singletonDemo先初始化再進行實例化,防止雙重校驗鎖失效
// private static volatile SingletonDemo singletonDemo = null;
// private SingletonDemo(){}
// public static SingletonDemo getInstance(){
// if (singletonDemo == null){
// synchronized (SingletonDemo.class){
// if (singletonDemo == null){
// singletonDemo = new SingletonDemo();
// }
// }
// }
// return singletonDemo;
// }
// 方式四:使用靜態內部類實現(常用)
// private static class SingletonHolder{
// public static SingletonDemo singletonDemo = new SingletonDemo();
// }
// private SingletonDemo(){
// }
// public static SingletonDemo getInstance(){
// return SingletonHolder.singletonDemo;
// }
// 方式五:枚舉方式(不常用)
}