/** * 饿汉式 */ class SingletonHungery{ private static SingletonHungery s = new SingletonHungery(); private SingletonHungery(){ } public static SingletonHungery getInstance(){ return s; } } /** * 懒汉式 */ class SingletonLazy{ private static SingletonLazy s; private SingletonLazy(){ } public static SingletonLazy getInstance(){ if(s == null) { s = new SingletonLazy(); } return s; } } public class SingletonDemo { public static void main(String[] args) { SingletonHungery s1 = SingletonHungery.getInstance(); SingletonHungery ss1 = SingletonHungery.getInstance(); System.out.println(s1 == ss1); SingletonLazy s2 = SingletonLazy.getInstance(); SingletonLazy ss2 = SingletonLazy.getInstance(); System.out.println(s2 == ss2); } }