如果我有靜態方法的類(固定行爲),那麼什麼是需要單例(狀態是固定的)類?使用單例類和類與靜態方法有什麼區別?
3
A
回答
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#語言的接口類型的更詳細的例子。
1
我認爲的最好的論據之一使用單,而不是純粹的靜態方法的類是,它可以更容易地引入多個實例,如果這真可謂是以後需要。在沒有根本理由將類限制爲單個實例的情況下,應用程序並不少見,但作者沒有設想任何代碼的擴展,並且發現使用靜態方法更容易。然後,當你想要延長應用程序時,要做到這一點就困難得多。
能夠替換實例進行測試(或其他原因)也是一個很好的觀點,並且能夠實現一個接口也有助於此。
相關問題
- 1. 什麼是靜態類與只有靜態方法的類之間的區別?
- 2. 非靜態類中的靜態方法和靜態類中的靜態方法有什麼區別?
- 3. 靜態結構方法和靜態類方法有什麼區別?
- 4. 將靜態方法放入靜態類並將實例方法放入靜態類中有什麼區別?
- 5. 靜態類和非靜態類有什麼區別?
- 6. 靜態方法和非靜態方法有什麼區別?
- 7. 靜態類和單例類的設計模式有什麼區別?
- 8. 靜態函數與類的靜態指針有什麼區別
- 9. 在Ruby中,類方法和類的單例方法有什麼區別?
- 10. 所有靜態方法和應用單例模式有什麼區別?
- 11. 靜態類和單一類的主要區別是什麼
- 12. 類方法或靜態變量,有什麼區別?
- 13. 公共靜態,公共和靜態方法有什麼區別?
- 14. 抽象類和靜態類之間有什麼區別?
- 15. PHP靜態類和單例類之間的確切區別是什麼
- 16. 擴展方法和靜態方法有什麼區別?
- 17. 類別和類方法有什麼區別?
- 18. 靜態屬性和單例之間有什麼區別?
- 19. 具有靜態方法的靜態類和具有靜態方法的常規類之間有什麼不同?
- 20. 實例化一個類並使用它的方法和靜態方法並使用它們而不實例化類之間有什麼區別
- 21. 單例類中的私有靜態變量和私有實例變量有什麼區別?
- 22. 使用Typescript和Sinon測試單例類中的靜態方法
- 23. 單例類與靜態方法相同類
- 24. Objective-C中的實例方法和類方法有什麼區別?
- 25. 繼承與類別有什麼區別
- 26. Debug類和Trace類有什麼區別?
- 27. ConfigurationManager類和Settings類有什麼區別?
- 28. HostingEnvironment類和HttpRuntime類有什麼區別?
- 29. 子類和子類有什麼區別?
- 30. java.awt.Rectangle類和java.awt.geom.Rectangle2D.Double類有什麼區別?
單例類可以實現一個接口。靜態方法不需要額外的對象。 – 2011-06-09 10:16:26
儘管針對不同的語言,這個問題是100%相關的:http://stackoverflow.com/questions/352348/static-classes-in-c – spender 2011-06-09 10:16:56
在singletone中,所有的方法將被一個實例調用,而在另一個方面他們會由Class直接調用。 – 2011-06-09 10:18:43