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

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


当前回答

这是一篇好文章:http://javarevisited.blogspot.com.au/2013/03/difference-between-singleton-pattern-vs-static-class-java.html

静态类

具有所有静态方法的类。更好的性能(静态方法在编译时绑定)无法重写方法,但可以使用方法隐藏。(Java中隐藏的方法是什么?甚至JavaDoc的解释都令人困惑)公共级动物{公共静态void foo(){System.out.println(“动物”);}}公共课猫延伸动物{public static void foo(){//隐藏Animal.foo()System.out.println(“类别”);}}

辛格尔顿

只能实例化一次的对象。方法可以被重写(为什么Java不允许重写静态方法?)比静态方法更容易模拟更善于保持状态

总之,我只使用静态类来保存util方法,而使用Singleton来处理其他所有事情。


编辑

静态类也被延迟加载。谢谢@jmoreno(静态类初始化何时发生?)静态类的方法隐藏。谢谢@MaxPeng。

其他回答

从测试角度来看,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模拟静态,但并非所有产品都可以使用它。

与静态类相比,Singleton模式有几个优点。首先,单例可以扩展类和实现接口,而静态类不能(它可以扩展类,但不继承它们的实例成员)。单例可以延迟或异步初始化,而静态类通常在首次加载时初始化,这会导致潜在的类加载器问题。然而,最重要的优点是,可以在不强迫用户假设只有一个实例的情况下以多态的方式处理单态。

为了说明Jon的观点,如果Logger是一个静态类,下面所示的操作是无法完成的。类SomeClass希望ILogger实现的一个实例传递到其构造函数中。

Singleton类对于实现依赖注入非常重要。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {

            var someClass = new SomeClass(Logger.GetLogger());
        }


    }

    public class SomeClass 
    {
        public SomeClass(ILogger MyLogger)
        {

        }
    }

    public class Logger : ILogger
    {
        private static Logger _logger;
        private Logger() { }

        public static Logger GetLogger()
        {
            if (_logger==null)
            {
                _logger = new Logger();
            }

            return _logger;
        }

        public void Log()
        {

        }

    }


    public interface ILogger
    {
         void Log();
    }
}

静态类别:-

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

辛格尔顿:-

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

一个显著的区别是Singleton附带的不同实例化。

对于静态类,它由CLR创建,我们无法控制它。使用singleton,对象在尝试访问的第一个实例上实例化。