单例模式

单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。


注意:

  1. 单例类只能有一个实例。
  2. 单例类必须自己创建自己的唯一实例。
  3. 单例类必须给所有其他对象提供这一实例。

一、双重检查DCL

public class Man {
    //DCL单例模式
    private static Man man = null;

    private Man() {
        //限制实例化
    }

    public static Man getInstance(){
        if (null == man){
            synchronized (man){
                if (null == man){
                    //DoubleCheck 双重检查
                    man = new Man();
                }
            }
        }
        return man;
    }
}

二、使用枚举实现

public enum  Singleton {
    //实现单例模式最简单、最佳的方法。自动支持序列化机制
    INSTANCE;

    public void noNameMethod(){
        //whatever
    }

    public static void main(String[] args) {
        Singleton instance = Singleton.INSTANCE;
        instance.noNameMethod();
    }

}

三、饿汉式单例(直接实例化)

public class  Singleton {

    //饿汉式,线程安全。可能会产生垃圾对象
    private static Singleton singleton = new Singleton();

    private Singleton(){}

    public static Singleton getInstance(){
        return singleton;
    }

}

四、懒汉式(线程不安全)

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;  
    }  
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值