博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
读《HeadFirst设计模式》笔记之单例模式
阅读量:7172 次
发布时间:2019-06-29

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

  hot3.png

单例模式:确保一个类只有一个实例,并提供一个全局访问点。即多次new对象,只能获取同一个对象。

实现方式一:懒汉模式(线程不安全)

public class Singleton {    private static Singleton instance;    private Singleton() {}    public Singleton getInstance() {        if (instance == null) {            instance = new Singleton();        }        return instance;    }}

实现方式二:饿汉模式(线程安全)

public class Singleton {    private static Singleton instance = new Singleton();    private Singleton() {}    public Singleton getInstance() {        return instance;    }}

构造函数是私有的,外部不能直接创建对象,只能通过静态方法getInstance()方法获取对象。

转载于:https://my.oschina.net/suyain/blog/1924582

你可能感兴趣的文章
CRF 及CRF++ 安装与解释
查看>>
SQL Server 合并复制的Article可以指定单个对象的更新方向
查看>>
hreadPoolExecutor使用和思考(上)-线程池大小设置与BlockingQueue的三种实现区别
查看>>
npm常用命令
查看>>
String,StringBuffer和StringBuilder三者的讲解
查看>>
Understanding Digital Raw Capture
查看>>
(轉貼) 康乃爾筆記法(Cornell Method) (雜項)
查看>>
(原創) unnamed object的多型只能使用reference (C/C++)
查看>>
10种有用的CSS技巧
查看>>
linux命令tree用法详解
查看>>
matlab练习程序(TV模型图像修复)
查看>>
用户接口(UI)设计的 20 条原则
查看>>
Windows Azure HandBook (3) 浅谈Azure安全性
查看>>
div+css布局入门
查看>>
Linux 下Apache和Resin的安装
查看>>
HDU 2710 Max Factorv (素数模板 & 多种解法)
查看>>
Linux 启动流程
查看>>
获得汉字字符串的首个拼音字母的缩写
查看>>
RegularExpressionValidator控件与常用验证正则表达式大全小结
查看>>
Zookeeper集群的安装和使用
查看>>