今天朋友找我給做道題,雙例模式,我是沒聽說過,都說是單例模式和多例模式,
也不知道雙例模式什麼時候用,就簡單寫了一個案例,不知道對不對,個人感覺蠻對的,雙例就是單例+單例,廢話不說了!!!!
/* *單例模式 調用方法 Singleton singleton = Singleton.getSingleton(); singleton.getValue("我是單例模式"); */ public class Singleton { private static Singleton singleton = null; public static Singleton getSingleton(){ if(singleton==null){ return singleton = new Singleton(); }else{ return singleton; } } public String getValue(String name){ return name; } } /* *雙例模式,如果是三例模式就吧len參數改成3 調用方法 Doubleton doubleton = Doubleton.getDoubleton(); doubleton.getValue("我有兩個實例!"); */ import java.util.ArrayList; import java.util.List; import java.util.Random; public class Doubleton { private static List<Doubleton> list = new ArrayList<Doubleton>(); private static int len = 2; static{ for(int i=0;i<len;i++){ list.add(new Doubleton()); } } public static Doubleton getDoubleton (){ Random random = new Random(); int current = random.nextInt(len); return (Doubleton)list.get(current); } public String getValue(String name){ return name; } }
希望大牛們給指點指點對不對,在此感謝!!!!