单例静态方法变量

singleton static method variables

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

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

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

static 成员来操纵你的单例是没有意义的,因为单例模式旨在创建 return class 的单个实例。

假设这段代码:

MySingleton.getInstance().foo();

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

MySingleton.foo();

但在这种情况下,这意味着单例实例不需要 returned,而仅由 class 本身在幕后操纵。 确保 class 只有一个实例并且 提供一个全局访问点并不是单例模式的意图

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

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

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;
  }

}

创建一个 class 只能存在一个实例并允许访问它 public 最终 class 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;
  }

}

除非您个人出于某种原因需要一个对象实例,否则我想不出功能上的差异。