簡體   English   中英

Java API中的單例類的示例

[英]Examples of singleton classes in the Java APIs

Java API中Singleton設計模式的最佳示例是什么? Runtime類是單例嗎?

只有兩個例子浮現在腦海中:

另見


更新 :回答PeterMmm的(目前已刪除?)評論(詢問我是如何知道它是單例),檢查javadoc和源代碼:

public class Runtime {
    private static Runtime currentRuntime = new Runtime();

    /**
     * Returns the runtime object associated with the current Java application.
     * Most of the methods of class <code>Runtime</code> are instance 
     * methods and must be invoked with respect to the current runtime object. 
     * 
     * @return  the <code>Runtime</code> object associated with the current
     *          Java application.
     */
    public static Runtime getRuntime() { 
        return currentRuntime;
    }

    /** Don't let anyone else instantiate this class */
    private Runtime() {}

它每次都返回相同的實例,並且它有一個private構造函數。

注意單身人士應謹慎使用和反思。 在實施單身人士之前,請考慮反對單身人士和你的情況。 過度使用單例是一種反模式 - 類似於全局變量。

Singleton Wiki文章

單身人士的Java Dev

為什么單身人士是邪惡的

我過去曾經使用它們,看到它們有一些好處。 當我試圖與他們一起進行測試驅動開發時,我也非常生氣,因為他們是邪惡的一個領域。 同樣繼承它們會導致一些難以理解的行為 - 至少在Python中 - 我不確定在Java中。 一般來說,你只是因為這個而不這樣做。 所以像線程一樣,這些看起來好像是一個好主意然后你遇到了陷阱並且意識到這可能畢竟不是那么好。

這適用於Swing: SingleFrameApplication 看看這個演示文稿,它精彩地描述了它是如何工作的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM