java 多种单例模式

单例设计模式

Singleton是一种创建型模式,指某个类采用Singleton模式,则在这个类被创建后,只可能产生一个实例供外部访问,并且提供一个全局的访问点。

(1) 将采用单例设计模式的类的构造方法私有化(采用private修饰)。

(2) 在其内部产生该类的实例化对象,并将其封装成private static类型。

(3) 定义一个静态方法返回该类的实例。

饿汉式天生就是线程安全的,可以直接用于多线程而不会出现问题,懒汉式本身是非线程安全的

饿汉式(线程安全 但效率比较低 )

public class Singleton_1 {
    //饿汉式
    private Singleton_1() {
    }

    private static Singleton_1 instance = new Singleton_1();

    public static Singleton_1 GetInstance() {
        return instance;
    }
}

懒汉式

public class Singleton_2 {
    // 懒汉式
    private Singleton_2() {

    }

    private static Singleton_2 instance = null;

    public static Singleton_2 getInstance(){
        if(instance == null)
            instance = new Singleton_2();
        return instance;
    }
}

懒汉式(线程安全)

public class Singleton_3 {
    // 线程安全的(双重检查锁定)
    private Singleton_3() {

    }

    private volatile static Singleton_3 instance = null;

    //同步方法
    public static synchronized Singleton_3 GetInstance() {
        if (instance == null)
            instance = new Singleton_3();
        return instance;
    }

    //同步代码块
    public static Singleton_3 GetInstanceBlock() {
        if (instance == null) {
            synchronized (Singleton_3.class) {
                if (instance == null)
                    instance = new Singleton_3();
            }
        }
        return instance;
    }
}

静态代码块

public class Singleton_4 {
    // 利用静态代码块
    private Singleton_4() {

    }

    private static class SingletonHolder {
        private final static Singleton_4 instance = new Singleton_4();
    }

    public static Singleton_4 getInstance() {
        return SingletonHolder.instance;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值