单例设计模式

x33g5p2x  于2022-03-06 转载在 其他  
字(0.7k)|赞(0)|评价(0)|浏览(276)

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;
    }
}

相关文章