//單例類示例 public class Singleton{ private static Singleton instance = null;//必須:靜態私有成員變量 //必須:私有構造類 private Singleton(){ } //靜態公有工廠方法,返回惟一實例,還不夠安全 /*public static Singleton getInstance(){ if (instance==null) { Synchronized(Singleton.class); instance =new Singleton(); } return instance; } */ //參考 http://blog.sina.com.cn/s/blog_75247c770100yxpb.html private static class SingletonHolder{ public final static Singleton instance = new Singleton(); } public static Singleton getInstance(){ return SingletonHolder.instance; } } //客戶端類 public class ClientSingleTon{ public static void main(String[] args) { Singleton s1= Singleton.getInstance(); Singleton s2= Singleton.getInstance(); System.out.println("s1==s2 "+(s1==s2)); } } 結果: s1==s2 true s1,s2值相等,內存地址相等,是同一個成員屬性