经过多方博客,文章参考,枚举是实现单例模式的最好方式
public enum Singleton { INSTANCE; public void businessMethod() { System.out.println("我是一个单例!"); } }
public class MainClass { public static void main(String[] args) { Singleton s1 = Singleton.INSTANCE; Singleton s2 = Singleton.INSTANCE; System.out.println(s1==s2); } }
将一个已有的类改造为单例类
public class Singleton { private Singleton(){ } public static enum SingletonEnum { SINGLETON; private Singleton instance = null; private SingletonEnum(){ instance = new Singleton(); } public Singleton getInstance(){ return instance; } } }
…… public static void main(String args[]) { Singleton s1 = SingletonEnum.SINGLETON.getInstance(); Singleton s2 = SingletonEnum.SINGLETON.getInstance(); System.out.println(s1==s2); } ……标签:Singleton,s2,s1,模式,单例,SingletonEnum,设计模式,public From: https://www.cnblogs.com/JavaYuYin/p/18015518