Java写一个单例类

- 饿汉式单例

类名,方法名可以变
public class Singleton {
    private Singleton(){}
上来生成一个对象,必须加static 静态 否则类无法直接调方法,因为他是一个成员代码块
    private static Singleton instance = new Singleton();
    public static Singleton getInstance(){
        return instance;
    }
}

懒汉式单例
public class Singleton {
    private static Singleton instance = null;
    private Singleton() {}
    public static synchronized Singleton getInstance(){
        if (instance == null) instance = new Singleton();
        return instance;
    }
}

--instance  实例


 

猜你喜欢

转载自blog.csdn.net/qq_39674417/article/details/113621703
今日推荐