/**Singleton with public final field**/ public class Elvis{ public static final Elvis INSTANCE = new Elvis(); private Elvis(){ ... } public void leaveTheBuilding(){ ... } } //Singleton with static factorypublic class Elvis{ private static final Elvis INSTANCE = new Elvis(); private Elvis(){ ... } public static Elvis getInstance(){ return INSTANCE;} public void leaveTheBuilding(){ ... }}//Enum singleton - the preferred approachpublic enum Elvis{ INSTANCE; public void leaveTheBuilding(){ ... }}
时间: 2024-11-09 07:21:00