单例模式之 饿汉式
public class Singleton { private final static Singleton s= new Singleton(); private Singleton() {} public static Singleton getInstance() { return s; } }
单例模式之 懒汉式
public class SingletonLazy { private static SingletonLazy s = null; private SingletonLazy() {} public static SingletonLazy getInstance() { if(s==null) { s= new SingletonLazy(); } return s; } }
public class TestSingleton { public static void main(String[] args) { Singleton s = Singleton.getInstance(); Singleton s2 =Singleton.getInstance(); Singleton s3 = Singleton.getInstance(); System.out.println(s ==s2); System.out.println(s ==s3); System.out.println(s.equals(s3)); SingletonLazy sl1 = SingletonLazy.getInstance(); SingletonLazy sl2 = SingletonLazy.getInstance(); System.out.println(sl1 == sl2); } }