2020java教程:单例模式

单例模式

单例(Singleton):只允许创建一个该类的对象。

方式1:饿汉式(类加载时创建,天生线程安全)

class Teacher{
    private static final Teacher t=new Teacher();
    private Teacher(){}
    public static Teacher getInstance(){
        return t;
    }
}

方式2:懒汉式(使用时创建,线程不安全,加同步)

class Teacher{
    private static Teacher t=null;
    private Teacher(){}
    public static synchronized Teacher getInstance(){
        if (t == null) {
            t=new Teacher();
        }
        return t;
    }
}

方式3:懒汉式(使用时创建,线程安全)

class Teacher{
    private Teacher(){}
    private static class Holder{
        static Teacher t=new Teacher();
    }
    public static Teacher getInstance(){
        return Holder.t;
    }
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *