Java 类的单个实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2062520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:07:39  来源:igfitidea点击:

Single instance of Java class

javasingleton

提问by giri

I wanna create a single instance of a class. How can I create a single instance of a class in Java?

我想创建一个类的单个实例。如何在 Java 中创建类的单个实例?

采纳答案by gpampara

To create a truly single instance of your class (implying a singleton at the JVM level), you should make your class a Java enum.

要创建您的类的真正单一实例(暗示 JVM 级别的单例),您应该使您的类成为 Java enum

public enum MyClass {
  INSTANCE;

  // Methods go here
}

The singleton pattern uses static state and as a result usually results in havoc when unit testing.

单例模式使用静态,因此在单元测试时通常会造成严重破坏。

This is explained in Item 3 of Joshua Bloch's Effective Java.

这在 Joshua Bloch 的 Effective Java 的第 3 条中有解释。

回答by Chathuranga Chandrasekara

use the singleton pattern.

使用单例模式。

Singleton pattern

单例模式

Update :

更新 :

What is the singleton pattern?The singleton pattern is a design pattern that is used to restrict instantiation of a class to one object

什么是单例模式?单例模式是一种设计模式,用于将类的实例化限制为一个对象

回答by Shane

Very basic singleton.

非常基本的单例。

public class Singleton {
  private static Singleton instance;

  static {
    instance = new Singleton();
  }

  private Singleton() { 
    // hidden constructor
  }    

  public static Singleton getInstance() {
    return instance;
  }
}

You can also use the lazy holder pattern as well

您也可以使用懒惰的持有人模式

public class Singleton {

  private Singleton() { 
    // hidden constructor
  }

  private static class Holder {
    static final Singleton INSTANCE = new Singleton();
  }

  public static Singleton getInstance() {
    return Holder.INSTANCE;
  }
}

This version will not create an instance of the singleton until you access getInstance(), but due to the way the JVM/classloader handles the creation on the inner class you are guaranteed to only have the constructor called once.

在您访问 getInstance() 之前,此版本不会创建单例的实例,但由于 JVM/类加载器处理内部类创建的方式,您可以保证只调用一次构造函数。

回答by user2001977

In Java, how can we have one instance of the BrokerPacket class in two threads? 

So that all the threads update store the different BrokerLocation in one location array. For example:

以便所有线程更新将不同的 BrokerLocation 存储在一个位置数组中。例如:

class BrokerLocation implements Serializable {
    public String  broker_host;
    public Integer broker_port;

    /* constructor */
    public BrokerLocation(String host, Integer port) {
        this.broker_host = host;
        this.broker_port = port;
    }
}


public class BrokerPacket implements Serializable {
    public static BrokerLocation locations[];   

}