单例模式(JAVA)

来源:互联网 发布:淘宝化妆品上新技巧 编辑:程序博客网 时间:2024/06/07 12:44

单例模式(Singleton)

class Singleton {    private static Singleton sInstance;//缓存当前对象,而且必须为static,因为要被下面的静态方法调用。    public static Singleton getInstance(){//必须为static,因为调用该方法时,还不存在对象。        if (sInstance == null) {            sInstance = new Singleton();        }        return sInstance;    }    private Singleton() {//必须为private,就是为了不让别的类new 当前对象    }}class Test{    public static void main(String args[]){        Singleton.getInstance();        System.out.println("Hello Worle!");    }}
0 0
原创粉丝点击