设计模式之单例模式
来源:互联网 发布:网络信息 编辑:程序博客网 时间:2024/06/06 13:05
1 单例模式
单例模式指的是一个类仅有一个实例,并提供一个访问它的全局访问点。
它的类图为
2 创建方式
2.1 饿汉式
package DesignPatterns;public class Singleton2 {// 饿汉式private static Singleton2 instance = new Singleton2();private Singleton2() {}public static Singleton2 getInstance() {return instance;}}
简单粗暴,类加载的时候就会初始化对象,会造资源浪费,线程安全。
2.2 懒汉式
package DesignPatterns;public class Singleton1 {// 懒汉式private static Singleton1 instance = null;private Singleton1() {}public static Singleton1 getInstance() {if (instance == null) {instance = new Singleton1();}return instance;}}具有延迟加载的好处,但是线程不安全
2.3 懒汉式,线程安全
package DesignPatterns;public class Singleton3 {// 懒汉式,线程安全private static Singleton3 instance = null;private Singleton3() {}public static synchronized Singleton3 getInstance() {if (instance == null) {instance = new Singleton3();}return instance;}}线程安全,使用了同步会造成效率降低,因为对象只需要初始化一次,之后无需初始化,也就不需要同步
2.4 懒汉式,双重检验锁
package DesignPatterns;public class Singleton4 {// 懒汉式,双重检验锁private static Singleton4 instance = null;private Singleton4() {}public static Singleton4 getInstance() {if (instance == null) {synchronized (Singleton4.class) {if (instance == null) {instance = new Singleton4();}}}return instance;}}大大减少了不需要同步的时机,第二个判空的原因:在对象为空的时候,存在多个线程要初始化的情况,只有先获得锁的线程才可以实例化一个对象,其他竞争的线程不能再实例一个对象。
2.5 静态内部类
package DesignPatterns;public class Singleton5 {// 静态内部类private Singleton5() {}private static class SingletonHolder{private static Singleton5 instance = new Singleton5();}public static Singleton5 getInstance() {return SingletonHolder.instance;}}
由于类的加载机制,静态属性只会被加载一次,使用内部类到达了延迟实例化对象的效果。
阅读全文
0 0
- 设计模式之 单例设计模式
- 设计模式之 单例设计模式
- 设计模式之单例设计模式
- 设计模式之-----------单例设计模式
- 设计模式之:单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之-单例设计模式
- 设计模式之单例设计模式 标签: 设计模式
- 设计模式之单例
- 设计模式之单例
- 设计模式之 单例
- Unity协程的作用
- 基于HDP2.6.0.3-8的Hadoop TestDFSIO、mrbench和nnbench是三个广泛被使用的测试
- vue 拖拽功能
- 项目打包,postman提交json数据
- UE4_ar项目经验
- 设计模式之单例模式
- zend studio打开右侧方法预览框
- 机器学习第二章模型评估与选择笔记(前篇)
- php 输出错误信息及设置错误级别
- LINUX线程分离
- 统计学习导论 Chapter3--Linear Regression
- CPU与代码优化(2):关于高速缓存命中问题的实验(Unity内)与研究
- 如何查看Android设备的ABI
- shell基础04函数