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;
// }
// 方式五:枚举方式(不常用)
}
java中单例模式的四种常用实现方式
猜你喜欢
转载自blog.csdn.net/u013804636/article/details/107063792
今日推荐
周排行