标签:
单例模式分为两种,懒汉式和饿汉式。区别在于创建实例的时机。饿汉式在该类加载时创建实例,懒汉式则在需要获取时才进行创建。
package Create.f.Singleton; public class Singleton { private Singleton(){ } protected static Singleton getInstance(){ System.out.println("获取Singleton单例对象"); return instance; } private static Singleton instance = new Singleton(); //饿汉式 注意此时线程安全 }
package Create.f.Singleton; //懒汉式 public class Singleton2 { private static Singleton2 instance = null; private Singleton2(){ } protected static synchronized Singleton2 getInstance(){ if(instance == null){ System.out.println("初始化Singleton2单例对象"); instance = new Singleton2(); } return instance; } }
package Create.f.Singleton; public class Client { public static void main(String[] args) { Singleton singleton = Singleton.getInstance(); Singleton s = Singleton.getInstance(); System.out.println("是否同个对象:" + (singleton == s)); Singleton2 s2 = Singleton2.getInstance(); Singleton2 s3 = Singleton2.getInstance(); Singleton2 s4 = Singleton2.getInstance(); System.out.println("是否同个对象:" + (s2 == s3 && s3 == s4)); } }
标签:
原文地址:http://www.cnblogs.com/ciade/p/5095328.html