博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java设计模式---单例模式
阅读量:7126 次
发布时间:2019-06-28

本文共 1766 字,大约阅读时间需要 5 分钟。

单例模式的几种实现方法,具体如下:

##懒汉模式

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 = new Singleton();    private Singleton(){}    public static Singleton getInstance(){        return instance;    }}复制代码

优点

  • 多线程安全

缺点

  • 加载类时就初始化完成,无法延时加载

##双重检查

public class Singleton {    private static Singleton instance ;    private Singleton(){}    public static Singleton getInstance(){        if (instance == null){            synchronized (Singleton.class){                if (instance == null){                    instance = new Singleton();                }            }        }        return instance;    }}复制代码

优点

  • 多线程安全
  • 延迟加载

缺点

  • 同步耗时

##静态内部类

public class Singleton {    private Singleton(){}    public static Singleton getInstance(){        return SingletonHolder.instance;    }    private static class SingletonHolder {        private static Singleton instance = new Singleton();    }}复制代码

优点

  • 多线程安全
  • 延迟加载
  • 耗时短(与双重检查相比)

##用缓存实现

public class Singleton {    private static final String KEY = "instance";    private static Map
map = new HashMap<>(); private Singleton(){} public static Singleton getInstance(){ Singleton singleton ; if (map.get(KEY) == null){ singleton = new Singleton(); map.put(KEY, singleton); } else { singleton = map.get(KEY); } return singleton; }}复制代码

优点

  • 线程安全

缺点

  • 占用内存较大

##枚举模式

public enum Singleton {    instance;    public void operate(){}}复制代码

优点

  • 简洁

缺点

  • 占用内存大(Android官方不推荐使用枚举)

更多文章请移步我的博客:

转载地址:http://dxael.baihongyu.com/

你可能感兴趣的文章
[vs2008]Visual Studio 2008 SP1添加或删除功能提示查找SQLSysClrTypes.msi文件
查看>>
JS 设计模式二(封装)
查看>>
JavaScript “跑马灯”抽奖活动代码解析与优化(一)
查看>>
为什么我们选择 segmentfault 写作?
查看>>
多模型融合推荐算法在达观数据的运用
查看>>
JDK 11 马上就要来了!JDK 12 还会远吗?
查看>>
Kali Linux 2019.1 发布,Metasploit 更新到 5.0 版本
查看>>
【mysql的设计与优化专题(1)】ER图,数据建模与数据字典
查看>>
Jibo’s Name: How did we pick it?
查看>>
device's media capture mechanism,利用input:file调用设备的照相机/相册、摄像机、录音机...
查看>>
BroadLink:三款新品力求无障碍人机交互,三大平台分三期对外开放 ...
查看>>
掌门1对1获3.5亿美元E-1轮融资,华人文化产业基金、中金甲子基金等投资 ...
查看>>
Unity中的通用对象池
查看>>
ORA-00600: internal error code, arguments: [16703], [1403], [28], [...
查看>>
忆芯科技发布新一代国产主控芯片STAR1000P!4月完成量产版本 ...
查看>>
如何用条码标签打印软件实现商品价签制定会员价 ...
查看>>
如何轻松实现个性化推荐系统
查看>>
Mysql高级查询 内连接和外连接详解
查看>>
基于AWS的电子商务网站架构——Web前端
查看>>
基于险企传统资源优势的“一核三环”规划——互联网平台建设
查看>>