菜单

曾嘉诚
发布于 2025-01-14 / 19 阅读
0
0

单例模式

什么是单例模式

单例模式是一种创建型设计模式,它确保一个类只有一个实例,并提供了一个全局访问点来访问该实例。

public class Hungry {
    
    private Hungry(){

    }
    private final static Hungry HUNGRY = new Hungry();

    public static Hungry getInstance(){
        return HUNGRY;
    }
}

一共有两种模式,一种为饿汉式,一种为懒汉式

饿汉式

在对象加载的时候,即使还没进行使用也会将对象的所有数据都一并加载,这样做会极大的消耗系统资源

public class Hungry {

    private byte[] data = new byte[1024*1024];
    private byte[] data1 = new byte[1024*1024];
    private byte[] data2 = new byte[1024*1024];
    private byte[] data3 = new byte[1024*1024];

    private Hungry(){

    }
    private final static Hungry HUNGRY = new Hungry();

    public static Hungry getInstance(){
        return HUNGRY;
    }
}

懒汉式

在对象要使用时再进行加载,节省系统资源

单线程

public class LazyMan {
    private LazyMan() {
    }
    private static LazyMan lazyMan;

    public static LazyMan getInstance() {
        if (lazyMan == null) {
            lazyMan = new LazyMan();
        }
        return lazyMan;
    }
}

若有多个线程同时调用该方法,就会产生线程安全问题

多线程

在获取锁前,由于同步是一个相对昂贵的操作,会影响性能,所以先进行判断,可以提高性能,volatile 关键字是为了保证在多线程环境下的可见性,避免指令重排序导致的问题。

public class LazyMan {
    private LazyMan() {
        System.out.println(Thread.currentThread().getName()+"ok");
    }
    private volatile static LazyMan lazyMan;
    public static LazyMan getInstance() {
        if (lazyMan == null) {
            synchronized (LazyMan.class){
                if (lazyMan==null){
                    lazyMan = new LazyMan();
                }
            }
        }
        return lazyMan;
    }
}


评论