有簡(jiǎn)單又高效的方法可以實(shí)現(xiàn)單例模式,但沒有一種方式能在任何情況下都確保單例的完整性。
單例模式是指某個(gè)類只被實(shí)例化一次,用來(lái)表示全局或系統(tǒng)范圍的組件。單例模式常用于日志記錄、工廠、窗口管理器和平臺(tái)組件管理等。我認(rèn)為要盡量避免使用單例模式,因?yàn)橐坏?shí)現(xiàn)就很難改變或重載,而且會(huì)造成編寫測(cè)試用例困難、代碼結(jié)構(gòu)糟糕等問題。另外,下面文章中的單例模式是不安全的。
人們花大量的精力研究怎樣更好地實(shí)現(xiàn)單例模式,但有一種簡(jiǎn)單高效的實(shí)現(xiàn)方法。然而,沒有一種方法能在任何情況下都確保單例的完整性。閱讀下文,看看你是否認(rèn)同。
這種方法將構(gòu)造函數(shù)私有化,向外提供一個(gè)公有的static final對(duì)象:
1 2 3 4 5 | public class FooSingleton { public final static FooSingleton INSTANCE = new FooSingleton(); public void bar() { }} |
類加載時(shí),static對(duì)象被初始化,此時(shí)私有的構(gòu)造函數(shù)被第一次也是最后一次調(diào)用。即使在類初始化前有多個(gè)線程調(diào)用此類,JVM也能保證線程繼續(xù)運(yùn)行時(shí)該類已完整初始化。然而,使用反射和setaccessible(true)方法,可以創(chuàng)建其他新的實(shí)例:
1 2 3 4 | Constructor[] constructors = FooSingleton.class.getDeclaredConstructors();Constructor constructor = constructors[0];constructor.setAccessible(true);FooSingleton spuriousFoo = (FooSingleton) constructor.newInstance(new Object[0]); |
我們需要修改構(gòu)造函數(shù),使其免于多次調(diào)用,例如當(dāng)它被再次調(diào)用時(shí)拋出異常。如下這樣修改FooSingleton構(gòu)造函數(shù),可以防范此類攻擊:
1 2 3 4 5 6 7 8 9 10 11 12 | public class FooSingleton2 { private static boolean INSTANCE_CREATED; public final static FooSingleton2 INSTANCE = new FooSingleton2(); private FooSingleton2() { if (INSTANCE_CREATED) { throw new IllegalStateException("You must only create one instance of this class"); } else { INSTANCE_CREATED = true; } } public void bar() { }} |
這樣看起來(lái)安全一些了,但其實(shí)要?jiǎng)?chuàng)建新的實(shí)例還是一樣容易。我們只需修改INSTANCE_CREATED字段,再玩同樣的把戲就可以了:
1 2 3 4 5 6 7 | Field f = FooSingleton2.class.getDeclaredField("INSTANCE_CREATED");f.setAccessible(true);f.set(null, false);Constructor[] constructors = FooSingleton2.class.getDeclaredConstructors();Constructor constructor = constructors[0];constructor.setAccessible(true);FooSingleton2 spuriousFoo = (FooSingleton2) constructor.newInstance(new Object[0]); |
我們采取的任何防范措施都可能被繞過,所以此方案并不可行。
使用這種方法,公有的成員類似靜態(tài)工廠:
1 2 3 4 5 6 | public class FooSingleton3 { public final static FooSingleton3 INSTANCE = new FooSingleton3(); private FooSingleton3() { } public static FooSingleton3 getInstance() { return INSTANCE; } public void bar() { }} |
getInstance()方法返回的永遠(yuǎn)是同一個(gè)對(duì)象引用。雖然這個(gè)方案也無(wú)法防范反射,但還是有它的一些優(yōu)點(diǎn)。例如,可以在不改變API的情況下,改變單例的實(shí)現(xiàn)。getInstance()出現(xiàn)在幾乎所有的單例實(shí)現(xiàn)中,它也標(biāo)志著這真的是一個(gè)單例模式。
(譯者注:在軟件工程中,Initialization-on-demand holder 這個(gè)習(xí)語(yǔ)指的就是延遲加載的單例模式,參見維基百科)
如果希望盡可能延遲單例的創(chuàng)建(懶漢式加載),可以使用延遲初始化方法,當(dāng)getInstance()方法第一次調(diào)用時(shí)線程安全地創(chuàng)建單例。相比之前的方案當(dāng)?shù)谝淮我迷擃悤r(shí)就創(chuàng)建單例(餓漢式加載),這是一個(gè)進(jìn)步。如下:
1 2 3 4 5 6 7 8 9 10 | public class FooSingleton4 { private FooSingleton4() { } public static FooSingleton4 getInstance() { return FooSingleton4Holder.INSTANCE; } private static class FooSingleton4Holder { private static final FooSingleton4 INSTANCE = new FooSingleton4(); }} |
如果單例實(shí)現(xiàn)了序列化,它就要面臨另一個(gè)威脅。因此需要將所有字段聲明為transient(這樣它就不會(huì)被序列化)并提供一個(gè)自定義的readResolve()方法返回唯一實(shí)例INSTANCE的引用。
這里用枚舉作為單例INSTANCE的容器:
1 2 3 4 5 | public enum FooEnumSingleton { INSTANCE; public static FooEnumSingleton getInstance() { return INSTANCE; } public void bar() { }} |
根據(jù)java語(yǔ)言規(guī)范8.9,“Enum的final克隆方法保證枚舉永遠(yuǎn)無(wú)法被克隆,其特殊的序列化機(jī)制保證無(wú)法反序列化得到拷貝的對(duì)象。同時(shí),還禁止利用反射對(duì)枚舉進(jìn)行實(shí)例化。保證了這四個(gè)方面,在枚舉常量之外,就不會(huì)有其他同類的枚舉實(shí)例存在。”
這樣,我們似乎很簡(jiǎn)單地就防范了序列化、克隆和反射的攻擊。第一次看到這段話,我立刻想要證明它是錯(cuò)的。如下代碼所示,繞過這些保護(hù)是很容易的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | Constructor con = FooEnumSingleton.class.getDeclaredConstructors()[0]; Method[] methods = con.getClass().getDeclaredMethods(); for (Method method : methods) { if (method.getName().equals("acquireConstructorAccessor")) { method.setAccessible(true); method.invoke(con, new Object[0]); } } Field[] fields = con.getClass().getDeclaredFields(); Object ca = null; for (Field field : fields) { if (field.getName().equals("constructorAccessor")) { field.setAccessible(true); ca = field.get(con); } } Method method = ca.getClass().getMethod("newInstance", new Class[]{Object[].class}); method.setAccessible(true); FooEnumSingleton spuriousEnum = (FooEnumSingleton) method.invoke(ca, new Object[]{new Object[]{"SPURIOUS_INSTANCE", 1}}); printInfo(FooEnumSingleton.INSTANCE); printInfo(spuriousEnum);}private static void printInfo(FooEnumSingleton e) { System.out.println(e.getClass() + ":" + e.name() + ":" + e.ordinal());} |
執(zhí)行這段代碼,得到結(jié)果:
1 2 | class com.blogspot.minborgsjavapot.singleton.FooEnumSingleton:INSTANCE:0class com.blogspot.minborgsjavapot.singleton.FooEnumSingleton:SPURIOUS_INSTANCE:1 |
枚舉的缺點(diǎn)是它無(wú)法從另一個(gè)基類繼承,因?yàn)樗呀?jīng)繼承自java.lang.Enum。如果想要模擬這種繼承,可以參考我另一篇文章中介紹的混入模式(mixin pattern)。
枚舉的一個(gè)優(yōu)點(diǎn)是,如果你之后希望有“二例(dualton)”或“三例(tringleton)”,只需要增加新的枚舉實(shí)例即可。例如,有了一個(gè)單例的緩存之后,你也許還想給緩存引入多個(gè)層次。
前兩天在一群里看見有人推薦一個(gè)app叫問啊,就可以發(fā)題答題那種的,感覺就跟uber滴滴打車似的,一般這種軟件一上來(lái)就砸錢給紅包啥的,哥之前刷過uber的單有經(jīng)驗(yàn)!試驗(yàn)了幾次應(yīng)該可以刷,把注冊(cè)紅包和之前領(lǐng)的紅包錢套現(xiàn),目前我提了五十多,目測(cè)還能刷更多。ps,但是盡量要問技術(shù)相關(guān)的問題,不然容易被封。
有技術(shù)的可以自己試,不會(huì)的可以q我:QQ群290551701
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注