差異處
這裏顯示兩個版本的差異處。
Both sides previous revision 前次修改 下次修改 | 前次修改 | ||
java:basic:close_systemin_of_scanner [2016/11/30 11:35] tony [Solutions] |
java:basic:close_systemin_of_scanner [2023/06/25 09:48] (目前版本) |
||
---|---|---|---|
行 8: | 行 8: | ||
- 使用Decorator樣式,將System.in包裝在不會真的close的InputStream中。 | - 使用Decorator樣式,將System.in包裝在不會真的close的InputStream中。 | ||
- 使用Singleton樣式,大家都用同一個Global Scanner。 | - 使用Singleton樣式,大家都用同一個Global Scanner。 | ||
- | 以單元測試方便性來說,我比較偏愛Decorator方式。 | + | 第一個做法對於寫code有潔癖的人來說,不會去使用的。而第二和第三個做法,以單元測試方便性來說與,我比較偏愛Decorator方式;使用Singleton的作法,還要考慮到底是誰負責close。如果大家都說好,你可以透過shutdown hook去close。 |
- | ==== Decorator ==== | + | \\ |
- | 參考apache common io程式碼: | + | \\ |
+ | 分享decorator作法,參考apache common io程式碼: | ||
<code java> | <code java> | ||
public class CloseShieldInputStream extends ProxyInputStream { | public class CloseShieldInputStream extends ProxyInputStream { | ||
行 41: | 行 42: | ||
} | } | ||
</code> | </code> | ||
- | ==== Singleton ==== | ||
- | |||
===== Reference ===== | ===== Reference ===== | ||
行 49: | 行 48: | ||
* [[http://stackoverflow.com/questions/23621668/java-closing-scanner-and-resource-leak|java-closing-scanner-and-resource-leak]] | * [[http://stackoverflow.com/questions/23621668/java-closing-scanner-and-resource-leak|java-closing-scanner-and-resource-leak]] | ||
+ | ===== ===== | ||
+ | ---- | ||
+ | \\ | ||
+ | ~~DISQUS~~ |