Java单例设计模式

饿汉式

方式一:直接实例化饿汉式(简洁直观)

class Singleton1 {
    private static final Singleton1 INSTANCE = new Singleton1();
     private Singleton1(){
    }
}

方式二:枚举式(最简洁)

enum Singleton2{
    INSTANCE;
}

方式三:静态代码块饿汉式(适合复杂实例化)

class Singleton3{
    public static final Singleton3 INSTANCE;
    private String info;
    static {
        try {
            InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("single.properties");
            Properties properties = new Properties();
            properties.load(is);
            INSTANCE = new Singleton3(properties.getProperty("info"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    private Singleton3(String info){
        this.info = info;
    }
}

懒汉式

方式四:线程不安全(适用于单线程)

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

方式五:线程安全(适用于多线程)

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

方式六:静态内部类形式(适用于多线程)

class Singleton6 {
	private Singleton6(){
	}
    private static class Inner {
        private static final Singleton6 INSTANCE = new Singleton6();
    }
    public static Singleton6 getInstance() {
        return Inner.INSTANCE;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值