四种单例设计模式
来源:互联网 发布:cdn网宿和阿里云cdn 编辑:程序博客网 时间:2024/06/08 10:27
单例模式特点:
1、单例类只能有一个实例。
2、单例类必须自己创建自己的唯一实例。
3、单例类必须给所有其他对象提供这一实例。
设计模式:
一、饿汉方式的单例模式(线程安全,但效率比较低,一开始就要加载类 ,new一个对象)
/** *在类创建的同时就已经创建好一个静态的对象供系统使用,以后不再 *改变,所以天生是安全的 */public class Singleton { private Singleton(){}//私有构造器 private static final Singleton instance=new Singleton(); public static Singleton getInstance(){ return instance; }}
二、饱汉方式的设计模式(有多个线程访问时是不安全的,返回的不是同一个对象)
public class Singleton { private Singleton(){} private static Singleton instance; public static Singleton getInstance(){ if(instance==null){ instance=new Singleton(); } return instance; }}
三、设计模式(线程安全,但效率低,在一个时候只能有一个线程能访问,同时返回一个对象)
public class Singleton { private Singleton(){} private static Singleton instance; public static synchronized Singleton getInstance(){ if(instance==null){ instance=new Singleton(); } return instance; }}
四、设计模式(双重检查锁定,线程安全,效率高,能有多个线程访问)
public class Singleton { private Singleton(){} private static Singleton instance; public static Singleton getInstance(){ if(instance==null){ synchronized (Singleton.class){ if(instance==null){ instance=new Singleton(); } } } return instance; }}
附五:静态内部类单例设计模式(线程安全,避免了同步带来的性能影响)
public class Singleton { private Singleton() {} private static class MyHolder{ private static final Singleton INSTANCE=new Singleton(); } public static final Singleton getInstance(){ return MyHolder.INSTANCE; }}
0 0
- 四种单例设计模式
- Java中的四种单例设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式~~~~~~~~~~
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- Unity错误(3)—— java.lang.IllegalArgumentException: ResClass is not initialized
- Android.mk 简介(二)
- 设置字符串中为数字字符的属性
- MFC总结(12) -- 在mfc中使用线程 更新Progress Control(1)
- 获取当前网络状态
- 四种单例设计模式
- Xcode之lldb的技巧
- 非控件ajax举例
- eclipse 设置 jdk 1.8 与 android sdk的问题
- geohash算法
- Mahout推荐算法API详解
- 使用TCP/IP协议实现聊天程序
- object-c:委托(delegate)
- Kafka学习3_Kafka命令行常用命令说明