【问题标题】:singleton static method variables单例静态方法变量
【发布时间】:2018-08-12 10:18:34
【问题描述】:

所以我试图通过在字段中使用私有构造函数和私有静态最终新单例类对象来制作单例对象。

但我对这些方法会是什么感到困惑。所有方法都需要是静态的吗?所有字段都需要是静态的吗?

【问题讨论】:

  • 单例模式(实际上是一种反模式)非常在网络上的许多地方都有很好的记录。他们不以某种方式为你工作吗?这些样本中的任何/所有令人困惑的地方是什么?
  • 不需要刻薄的吉姆。我遇到的那些很短,没有字段或方法。仅仅是获得基本模式的骨架。如果你要努力打字,你也可以只输入用户“lexicore”所做的,这实际上很有帮助,并且需要减少 35% 的打字。
  • 重点是您应该在发布问题之前进行认真研究。提醒您这一点并不刻薄

标签: java methods static singleton field


【解决方案1】:

单例的(单个)实例已经是静态的,因此单例类的字段和方法都不需要是静态的。

【讨论】:

    【解决方案2】:

    static 成员来操作您的单例是没有意义的,因为单例模式旨在创建和返回一个类的单个实例。

    假设这段代码:

    MySingleton.getInstance().foo();
    

    如果 foo()static,为什么在调用 foo() 之前调用 getInstance()? 实例无法调用静态方法。
    所以这就足够了:

    MySingleton.foo();
    

    但在这种情况下,这意味着不需要返回单例实例,而只能由类本身在后台进行操作。 单例模式的目的不是确保一个类只有一个实例并提供一个全局访问点

    【讨论】:

      【解决方案3】:

      从技术上讲,您有两种方法来创建单例。

      创建一个完全静态的类,没有可用的构造函数

      public final class StaticSingelton{
      
        private final static String readOnlyField = "readMe";
        private int static writeOnlyField = -1;
        private double static readAndWriteField = -1;
      
        private StaticSingelton(){
          throw new IllegalAccessException();
        }
      
        public final static String getReadOnlyField(){
        return readOnlyField;
        }
        public final static void setWriteOnlyField(final int value){
        writeOnlyField = value;
        }
        public final static double getReadAndWriteField(){
        return readAndWriteField;
        }
        public final static void setReadAndWriteField(final double value){
        readAndWriteField = value;
        }
      
      }
      

      创建一个类,该类只能存在一个实例并允许访问它 公共最终类 InstanceSingelton{

      private final static InstanceSingelton instance = new InstanceSingelton();
      
        private final String readOnlyField = "readMe";
        private int writeOnlyField = -1;
        private double readAndWriteField = -1;
      
      private InstanceSingelton(){
        if(instance != null){
          throw new IllegalAccessException();
        }
      }
      
        public final static InstanceSingelton getInstance(){
           return instance;
        }
      
        public final String getReadOnlyField(){
        return readOnlyField;
        }
        public final void setWriteOnlyField(final int value){
        writeOnlyField = value;
        }
        public final double getReadAndWriteField(){
        return readAndWriteField;
        }
        public final void setReadAndWriteField(final double value){
        readAndWriteField = value;
        }
      

      }

      除非你个人出于某种原因需要一个对象实例,否则我想不出功能上有什么不同。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-10
        相关资源
        最近更新 更多