通过枚举类来实现单例模式 1234567891011121314151617 enum Single { Single; private () { } public void print(){ System.out.println("hello world"); }}public class SingleDemo { public static void main(String[] args) { Single a = Single.Single; a.print();} 通过静态内部类来实现 12345678910111213141516 public class Singleton{ private Singleton(){} private static class SingletonHandler { private static Singleton singleton = new Singleton(); } public static Singleton getInstance(){ return SingletonHandler.singleton; } public void someMethod(){ System.out.println("This's display!"); }} 饿汉式 1234567891011121314 public class Singleton{ private Singleton(){} private static Singleton singleton = new Singleton(); public static Singleton getInstance(){ return singleton; } public void someMethod(){ System.out.println("This's display!"); }} 赞微海报分享
近期评论