精華區beta java 關於我們 聯絡資訊
※ 引述《[email protected] (foolish)》之銘言: : ※ 引述《[email protected] (大學生)》之銘言: : > 可以示範一下嗎? : > 我沒看過這種方法 : > 我JAVA才學一年而已...XD : 一年!!! 好長的一段時間啊@@ : 那總有學到static method的用法吧 The Singleton Pattern有幾種方法 我只說我比較常用的一種 其實在Java API中就有採用這種方法 像Toolkit,Math,ImageIO就有這種味道 他的寫法就如這樣 public class Singleton{ static Singleton instance = new Singleton(); private Singleton(){ } public static Singleton getInstance(){ return instance; } ..... ...... } 當然也有人會這樣寫 public final class Singleton{ static public void method1(){ ..... } } 你可能會問這樣寫有啥用處咧? 這種寫法在寫Server程式時相當好用 如果你的Server有一個User Manager的module你就應該採用這種Design Pattern 讓你的User Manager的Reference不能直接new出來 以保證系統上每個User Manager的module都是同一份 例如: public class A{ Singleton instanceA = Singleton.getInstance(); } public class B{ Singleton instanceB = Singleton.getInstance(); } 在RunTime的時候 instanceA和instanceB就會是同一個reference. -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.123.105.36 ※ 編輯: calais007 來自: 140.123.105.36 (10/15 15:20)