【问题标题】:What is difference between using singleton class and class with static methods?使用单例类和使用静态方法的类有什么区别?
【发布时间】:2011-06-09 10:15:08
【问题描述】:

如果我有带有静态方法(固定行为)的类,那么单例(状态是固定的)类需要什么?

【问题讨论】:

标签: java


【解决方案1】:

使用单例可以更容易地在需要时替换实例,例如进行测试。

【讨论】:

    【解决方案2】:

    我认为使用单例而不是具有纯静态方法的类的最佳论据之一是,如果以后需要引入多个实例,它会更容易。没有根本原因将类限制为单个实例的应用程序并不少见,但作者并没有设想对他们的代码进行任何扩展,并且发现使用静态方法更容易。然后,当您以后想要扩展应用程序时,这样做会困难得多。

    能够替换实例以进行测试(或其他原因)也是一个优点,并且能够实现接口也对此有所帮助。

    【讨论】:

      【解决方案3】:

      下面的文章是用 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

      【讨论】:

        猜你喜欢
        • 2013-07-21
        • 2011-10-30
        • 2012-11-02
        • 2011-07-11
        • 1970-01-01
        • 1970-01-01
        • 2011-06-04
        • 2011-06-18
        • 2013-07-26
        相关资源
        最近更新 更多