遇到類似的問題:生產編號的產生,售票系統等資料需要同步,馬上想到單例模式....
例子代碼:
package Singleton;/** *@Description: 單例模式 *@author Potter *@date 2012-8-14 下午10:08:16 *@version V1.0 */public class App {public static void main(String[] args) {NumDevice g=NumDevice.getInstance();//Greedy2 g=Greedy2.INSTANCE;System.out.println(g.next());show();}public static void show(){NumDevice g=NumDevice.getInstance();//NumDevice2 g=NumDevice2.INSTANCE;System.out.println(g.next());}}
方法一:用類實現:
package Singleton;/** *@Description: 單例類 *@author Potter *@date 2012-8-14 下午10:01:45 *@version V1.0 */public class NumDevice {private final static NumDevice me=new NumDevice();private NumDevice(){}public static NumDevice getInstance(){return me;}private int count;public int next(){return count++;}}
方法二:用枚舉類
package Singleton;/** *@Description: 單例類 *@author Potter *@date 2012-8-14 下午10:01:45 *@version V1.0 */public enum NumDevice2 {INSTANCE;private int count;public int next(){return count++;}}