1.单例类
public class Singleton { private Singleton(){}; public void doSomething(){ System.out.println("do some thing"); } }
2.单例工厂类
package com.example.demo.entity; import java.lang.reflect.Constructor; public class SingletonFactory { private static Singleton singleton; static { try { Class cl= Class.forName(Singleton.class.getName()); //获得无参构造 Constructor constructor=cl.getDeclaredConstructor(); //设置无参构造是可访问的 constructor.setAccessible(true); singleton =(Singleton) constructor.newInstance(); } catch (Exception e) { e.printStackTrace(); } } public static Singleton getSingleton(){ return singleton; } }
3.场景类
package com.example.demo.entity; public class Client { public static void main(String[] args) { Singleton singleton = SingletonFactory.getSingleton(); singleton.doSomething(); } }