设计模式-单例

来源:互联网 发布:linux echo 串口 编辑:程序博客网 时间:2024/05/29 09:42

为了保持对象的一致性,实现对象只被创建一次,单例模式被经常用到,整理了几种常用的写法如下:

普通单例模式

基本满足日常使用的需要

public class Singleton {    private static Singleton instance;    public static Singleton getInstance() {        if (instance == null) {            instance = new Singleton ();        }        return instance;    }    private Singleton () {    }}
双重校验单例模式

应用于高并发情况

public class Singleton {    private static Singleton instance;    public static Singleton getInstance() {        if (instance == null) {            synchronized (Singleton .class) {                if (instance == null) {                    instance = new Singleton ();                }            }        }        return instance;    }    private Singleton () {    }}
Effective Java中提到的单元素枚举类型实现

无偿提供了序列化机制,可应对序列化及反射攻击

public enum Singleton {    INSTANCE;    public void test(){    }}
0 0