设计模式之单例模式
来源:互联网 发布:sql union怎么用 编辑:程序博客网 时间:2024/05/14 10:00
单例模式
基本知识
1、单例模式(Singleton)属于对象创建型模式,其目的是保证当前类只能创建一个对象。
2、实现步骤:
a、私有化构造器,使用private修饰符修饰构造方法;
b、提供静态的属性,静态属性也用private修饰符修饰;
c、提供一个静态的方法,返回在类内部所创建的对象;
3、分类:
a、饿汉式:当程序一启动就立即产生对象加载到内存
应用场景:对象比较大,非常消耗时间,空间换取时间。
优缺点:消耗了空间,节省了时间。
b、懒汉式(饱汉式):当请求到达时才产生对象放置到内存中
应用场景:对象比较小,消耗时间少,时间换取空间。
懒汉式单例模式
/** * 懒汉式:同步整个方法 */public class Singleton {//提供静态的私有的属性private static Singleton instance = null;//私有化构造器private Singleton(){}//提供一个静态方法,用户返回Singleton实例public static synchronized Singleton getInstance(){if(instance==null){instance = new Singleton();}return instance;}}
/** * 懒汉式:同步关键代码块 */public class Singleton {//提供静态的私有的属性private static Singleton instance = null;//私有化构造器private Singleton(){}//提供一个静态方法,用户返回Singleton实例public static Singleton getInstance(){if(instance==null){synchronized(Singleton.class){instance = new Singleton();}}return instance;}}
/** * 懒汉式:双重加锁检查 */public class Singleton {//提供静态的私有的属性private static Singleton instance = null;//私有化构造器private Singleton(){}//提供一个静态方法,用户返回Singleton实例public static Singleton getInstance(){if(instance==null){synchronized(Singleton.class){if(instance==null){instance = new Singleton();}}}return instance;}}
饿汉式单例模式
/** * 饿汉式:空间换取时间 */public class Singleton {//提供静态的私有的属性private static Singleton instance = new Singleton();//私有化构造器private Singleton(){}//提供一个静态方法,用户返回Singleton实例public static Singleton getInstance(){return instance;}}
0 0
- 设计模式之 单例设计模式
- 设计模式之 单例设计模式
- 设计模式之单例设计模式
- 设计模式之-----------单例设计模式
- 设计模式之:单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之-单例设计模式
- 设计模式之单例设计模式 标签: 设计模式
- 设计模式之单例
- 设计模式之单例
- 设计模式之 单例
- 为什么使用viewWithTag来访问Subview
- IOS svn 命令
- 建站开发常用资源
- 怎么获取Spring的ApplicationContext
- python数据结构与算法 37 树的实现
- 设计模式之单例模式
- JVM系列三:JVM参数设置、分析
- Ubuntu recovery mode找回密码
- C#读取Xml文件
- linux socket网络编程详解
- Unity3D C# MySql 简单的登录验证
- Android系统配置数据库注释(settings.db)
- ORACLE和SQL SERVER 分区索引的区别
- 使用Oracle SQLDeveloper连接数据库并创建用户