package singleton_pattern; public class SingleTonPattern { public static void main(String[] args) { SingleTon s1=SingleTon.getInstance(); // SingleTon s2=SingleTon.getInstance(); System.out.println(s1); SingleTon2 s3=SingleTon2.getInstance(); System.out.println(s3); SingleTon3 s4=SingleTon3.getInstance(); System.out.println(s4); SingleTon4 s5=SingleTon4.getInstance(); System.out.println(s5); } } class SingleTon{ //单例的必要 *** 作--构造方法私有化 private SingleTon() {} //创建静态私有成员变量new一个实例对象 private static SingleTon st=new SingleTon(); //公有方法返回 public static SingleTon getInstance() { return st; } } class SingleTon2{ //同样的配方,私有构造 private SingleTon2(){} //创建静态私有成员变量赋null private static SingleTon2 st=null; public static SingleTon2 getInstance() { if(st==null) st=new SingleTon2(); return st; } } class SingleTon3{ //同样的配方,私有构造 private SingleTon3(){} //创建静态私有成员变量赋null private static SingleTon3 st=null; public static SingleTon3 getInstance() { if(st==null) { synchronized (SingleTon3.class) { if(st==null)//双重判断,很nice st=new SingleTon3(); } } return st; } } class SingleTon4{ //同样的配方,私有构造 private SingleTon4(){} //静态内部类 private static class Instance{ private static SingleTon4 st=new SingleTon4(); } public static SingleTon4 getInstance() { return Instance.st; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)