gpt4 book ai didi

单例设计模式

转载 作者:知者 更新时间:2024-03-13 05:18:54 25 4
gpt4 key购买 nike

1.概念

保证一个类只有一个对象,并提供一个访问它的全局访问点

2.饿汉模式

package com.yl.demo.design;

//饿汉模式
public class SingleTon1 {
    private SingleTon1(){}
    private static SingleTon1 singleTon1 = new SingleTon1();

    public static SingleTon1 getInstance(){
        return singleTon1;
    }
}

3.懒汉模式

package com.yl.demo.design;

//懒汉模式
public class SingleTon2 {
    private SingleTon2(){}
    public static SingleTon2 singleTon2 = null;

    public static SingleTon2 getInstance(){
        if (singleTon2 == null) {
            singleTon2 = new SingleTon2();
        }
        return singleTon2;
    }
}

4.线程安全的懒汉模式

package com.yl.demo.design;

//线程安全的懒汉模式
public class SafeSingleTon {
    private SafeSingleTon(){}
    private static SafeSingleTon safeSingleTon = null;

    public static SafeSingleTon getInstance(){
        if (safeSingleTon == null) {
            synchronized(SafeSingleTon.class) {
                safeSingleTon = new SafeSingleTon();
            }
        }
        return safeSingleTon;
    }
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com