静态类和单例模式之间存在什么实际的区别?

两者都可以在没有实例化的情况下调用,两者都只提供一个“实例”,而且都不是线程安全的。还有其他区别吗?


当前回答

从测试角度来看,Singleton是更好的方法。与静态类不同,singleton可以实现接口,您可以使用mock实例并注入它们。

在下面的示例中,我将对此进行说明。假设您有一个使用getPrice()方法的方法isGoodPrice(。

提供getPrice功能的singleton:

public class SupportedVersionSingelton {

    private static ICalculator instance = null;

    private SupportedVersionSingelton(){

    }

    public static ICalculator getInstance(){
        if(instance == null){
            instance = new SupportedVersionSingelton();
        }

        return instance;
    }

    @Override
    public int getPrice() {
        // calculate price logic here
        return 0;
    }
}

getPrice的使用:

public class Advisor {

    public boolean isGoodDeal(){

        boolean isGoodDeal = false;
        ICalculator supportedVersion = SupportedVersionSingelton.getInstance();
        int price = supportedVersion.getPrice();

        // logic to determine if price is a good deal.
        if(price < 5){
            isGoodDeal = true;
        }

        return isGoodDeal;
    }
}


In case you would like to test the method isGoodPrice , with mocking the getPrice() method you could do it by:
Make your singleton implement an interface and inject it. 



  public interface ICalculator {
        int getPrice();
    }

最终Singleton实施:

public class SupportedVersionSingelton implements ICalculator {

    private static ICalculator instance = null;

    private SupportedVersionSingelton(){

    }

    public static ICalculator getInstance(){
        if(instance == null){
            instance = new SupportedVersionSingelton();
        }

        return instance;
    }

    @Override
    public int getPrice() {
        return 0;
    }

    // for testing purpose
    public static void setInstance(ICalculator mockObject){
        if(instance != null ){
instance = mockObject;
    }

测试等级:

public class TestCalculation {

    class SupportedVersionDouble implements ICalculator{
        @Override
        public int getPrice() { 
            return 1;
        }   
    }
    @Before
    public void setUp() throws Exception {
        ICalculator supportedVersionDouble = new SupportedVersionDouble();
        SupportedVersionSingelton.setInstance(supportedVersionDouble);

    }

    @Test
    public void test() {
          Advisor advidor = new Advisor();
          boolean isGoodDeal = advidor.isGoodDeal();
          Assert.assertEquals(isGoodDeal, true);

    }

}

如果我们选择使用静态方法来实现getPrice(),那么很难模拟getPrice)。您可以使用power mock模拟静态,但并非所有产品都可以使用它。

其他回答

在单例模式中,可以将单例创建为派生类型的实例,但不能使用静态类。

快速示例:

if( useD3D )
    IRenderer::instance = new D3DRenderer
else
    IRenderer::instance = new OpenGLRenderer

我将努力超越WTMI和WTL;DR响应。

单身者是一个物体的实例。。。句点

你的问题基本上是问类和该类的实例之间的区别。我认为这很清楚,不需要详细说明。

singleton的类通常采取步骤来确保构建一个实例;这很聪明,但不是必须的。

示例:var connection=connection.Instance;

假设这是Connection类:

public sealed class Connection 
{
    static readonly Connection _instance = new Connection();

    private Connection() 
    {
    }

    public static Connection Instance
    {
        get
        {
           return _instance;
        }
    } 
}

请注意,您可以在该类上抛出一个接口并模拟它以进行测试,这是静态类无法轻易做到的。

我同意这个定义:

单词“single”表示整个应用程序生命周期中的单个对象循环,因此范围在应用程序级别。静态不具有任何Object指针,因此作用域位于AppDomain级别。此外,两者都应实现为线程安全。

你可以发现其他有趣的区别:Singleton模式与静态类

静态类别:-

无法创建静态类的实例。当加载包含类的程序或命名空间时,由.NET Framework公共语言运行库(CLR)自动加载。我们不能将静态类传递给方法。我们不能将静态类继承到C#中的另一个静态类。具有所有静态方法的类。更好的性能(静态方法在编译时绑定)

辛格尔顿:-

您可以创建对象的一个实例并重用它。当用户请求时,首次创建Singleton实例。您可以创建singleton类的对象并将其传递给方法。Singleton类没有说明继承的任何限制。我们可以处理单例类的对象,但不能处理静态类的对象。方法可以被重写。可以在需要时延迟加载(静态类总是加载的)。我们可以实现接口(静态类不能实现接口)。

在许多情况下,这两者没有实际差异,特别是如果单例实例从未更改或更改非常缓慢,例如保持配置。

我想说,最大的区别是单例仍然是一个普通的JavaBean,而不是专门的仅静态Java类。正因为如此,单身汉在很多情况下都被接受;它实际上是默认的Spring框架的实例化策略。消费者可能知道也可能不知道它是一个被传递的单例,它只是把它当作一个普通的Javabean。如果需求发生变化,而单例需要成为原型,正如我们在Spring中经常看到的那样,它可以完全无缝地完成,而无需对消费者进行一行代码更改。

前面有人提到,静态类应该是纯过程的,例如java.lang.Math。在我看来,这样的类永远不应该被传递,它们永远不应该将静态final以外的任何属性作为属性。对于其他一切,使用单例,因为它更灵活,更易于维护。