单例模式的几种实现方式: 一:饿汉式单例 方式一:枚举方式获得单例对象 方式二:静态属性获得单例对象 方式三:静态方法获得单例对象 二:懒汉式单例 方式一:静态方法获得单例对象(线程安全) 方式二:内部类方式去获取单例对象
示例: 恶汉式:方式一 enum Singleton{ INSTANCE;//单例 } 恶汉式:方式二 class Singleton{ public static final Singleton INSTANCE = new Singleton();//单例 private Singleton(){} } 恶汉式:方式三 class Singleton{ private static final Singleton INSTANCE = new Singleton();//单例 private Singleton(){} public static Singleton getInstance(){ return INSTANCE; } } 懒汉式:方式一 class Singleton{ private static Singleton instance; public static Singleton getInstance(){ //存在线程安全问题(多线程的时候,不一定是单例) /*if(null == instance){ instance = new Singleton(); } return instance;*/ if(null == instance){ //提升代码效率,避免每一次都去走同步代码块 synchronized(Singleton.class){ if(null == instance){ instance = new Singleton(); } return instance; } } return instance; } } } 懒汉式:方式二 class Singleton{ private Singleton(){} private static class Inner{ public static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance(){ return Inner.INSTANCE; } } |
|