2011-06-09 50 views
3

如果我有靜態方法的類(固定行爲),那麼什麼是需要單例(狀態是固定的)類?使用單例類和類與靜態方法有什麼區別?

+2

單例類可以實現一個接口。靜態方法不需要額外的對象。 – 2011-06-09 10:16:26

+0

儘管針對不同的語言,這個問題是100%相關的:http://stackoverflow.com/questions/352348/static-classes-in-c – spender 2011-06-09 10:16:56

+0

在singletone中,所有的方法將被一個實例調用,而在另一個方面他們會由Class直接調用。 – 2011-06-09 10:18:43

回答

2

在單例中,如果需要更換實例,比如更容易進行測試。

0

下面的文章那麼在C#中,但我認爲這也同樣爲德的Java已經期待它可以幫助你瞭解

與接口

您可以使用單身與接口,就像任何其他用途單身類。在C#中,接口是契約,具有接口的對象必須滿足該接口的所有要求。

單身可以與接口使用

/// <summary> 
/// Stores signatures of various important methods related to the site. 
/// </summary> 
public interface ISiteInterface 
{ 
}; 

/// <summary> 
/// Skeleton of the singleton that inherits the interface. 
/// </summary> 
class SiteStructure : ISiteInterface 
{ 
    // Implements all ISiteInterface methods. 
    // [omitted] 
} 

/// <summary> 
/// Here is an example class where we use a singleton with the interface. 
/// </summary> 
class TestClass 
{ 
    /// <summary> 
    /// Sample. 
    /// </summary> 
    public TestClass() 
    { 
    // Send singleton object to any function that can take its interface. 
    SiteStructure site = SiteStructure.Instance; 
    CustomMethod((ISiteInterface)site); 
    } 

    /// <summary> 
    /// Receives a singleton that adheres to the ISiteInterface interface. 
    /// </summary> 
    private void CustomMethod(ISiteInterface interfaceObject) 
    { 
    // Use the singleton by its interface. 
    } 
} 

在這裏,我們可以使用單上接受的接口的任何方法。我們不需要一遍又一遍地重寫任何東西。這些是面向對象編程的最佳實踐。你可以在這裏找到關於C#語言的接口類型的更詳細的例子。

C# Singleton Pattern Versus Static Class

1

我認爲的最好的論據之一使用單,而不是純粹的靜態方法的類是,它可以更容易地引入多個實例,如果這真可謂是以後需要。在沒有根本理由將類限制爲單個實例的情況下,應用程序並不少見,但作者沒有設想任何代碼的擴展,並且發現使用靜態方法更容易。然後,當你想要延長應用程序時,要做到這一點就困難得多。

能夠替換實例進行測試(或其他原因)也是一個很好的觀點,並且能夠實現一個接口也有助於此。

相關問題