首页 > 代码库 > 简单的单例实现

简单的单例实现

单例模式是指该类只能有一个实例,所以必须隐藏类的构造函数,对外只提供一个创建对象的方法,

public class MyClass {
    public static void main(String args[]) {
       Single s = Single.getSingle();
       // Single s = new Single();
       System.out.println(s);
       Single s1 = Single.getSingle();
       if(s == s1){
           System.out.println("yes");
       }
       noSingle ns = new noSingle();
       noSingle ns1 = new noSingle();
       if(ns == ns1){
           System.out.println("yes");
       }else{
           System.out.println("no");
       }
    }
}
class Single{
    private static Single s = null;
    private Single() {}
    public static Single getSingle(){
        if(s == null){
            s = new Single();
        }
        return s;
    }
    public String toString(){
        return "this is a single";
    }
}
class noSingle{
    
}

  执行结果:

this is a single
yes
no

注意:不能再成员函数内部定义static变量!!

简单的单例实现