2011-06-09 80 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

我认为的最好的论据之一使用单,而不是纯粹的静态方法的类是,它可以更容易地引入多个实例,如果这真可谓是以后需要。在没有根本理由将类限制为单个实例的情况下,应用程序并不少见,但作者没有设想任何代码的扩展,并且发现使用静态方法更容易。然后,当你想要延长应用程序时,要做到这一点就困难得多。

能够替换实例进行测试(或其他原因)也是一个很好的观点,并且能够实现一个接口也有助于此。

相关问题