设计模式之单例模式
来源:互联网 发布:空气净化器选购 知乎 编辑:程序博客网 时间:2024/06/13 06:19
单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。
单例模式:系统运行期间,有且只有一个实例
1、单例类只能有一个实例。
2、单例类必须自己创建自己的唯一实例。
3、单例类必须给所有其他对象提供这一实例。
单例模式保证一个类只有一个实例,并提供一个访问它的全局访问点,避免一个全局使用类频繁的创建与销毁,节省系统资源,单例类的构造函数是私有的。
单例模式的实现方式:
1、懒汉模式(Lazy初始化,线程不安全):第一次调用才初始化,避免浪费内存。必须加锁synchronized才能保证单例(此时多线程安全),但加锁会影响效率
public class Singleton { //多线程不安全 private static Singleton instance; private Singleton (){} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
public class Singleton { //多线程安全 private static Singleton instance; private Singleton (){} public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
2、饿汉模式(不Lazy初始化,线程安全):类初始化时加载,浪费内存
public class Singleton { //没有加锁,执行效率高,常用但容易产生垃圾对象 private static Singleton instance = new Singleton(); private Singleton (){} public static Singleton getInstance() { return instance; } }
3、双检锁/双重校验锁(DCL,即 double-checked locking)public class Singleton { private volatile static Singleton singleton; private Singleton (){} public static Singleton getSingleton() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }
4、登记式/静态内部类
public class Singleton { private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } private Singleton (){} public static final Singleton getInstance() { return SingletonHolder.INSTANCE; } }
5、枚举
public enum Singleton { INSTANCE; public void whateverMethod() { } }
阅读全文
0 0
- 设计模式之 单例设计模式
- 设计模式之 单例设计模式
- 设计模式之单例设计模式
- 设计模式之-----------单例设计模式
- 设计模式之:单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之-单例设计模式
- 设计模式之单例设计模式 标签: 设计模式
- 设计模式之单例
- 设计模式之单例
- 设计模式之 单例
- python语言 pyspark中dataframe修改列名
- Python3 读取文件内容万金油方法
- andengine_box2d在高版本androd手机上出现问题
- sdnu 1009
- usaco6.2.1 Calf flac
- 设计模式之单例模式
- java编译并打包成可执行jar和exe文件
- 查看域名对应ip
- FreeMarker
- 系统服务的控制
- redhat6.6的nfs服务端配置
- 大数据产品推荐:百融信贷决策审批系统
- 4分钟学会网页样式
- 关于使用https请求微信乱码问题