简体   繁体   English

Java类的单个实例

[英]Single instance of Java class

I wanna create a single instance of a class. 我想创建一个类的单个实例。 How can I create a single instance of a class in Java? 如何在Java中创建一个类的单个实例?

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. 约书亚布洛赫的Effective Java的第3项对此进行了解释。

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 /类加载器处理内部类创建的方式,因此保证只有一次调用构造函数。

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 单例模式是一种设计模式,用于将类的实例化限制为一个对象

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. 这样所有线程都会更新将不同的BrokerLocation存储在一个位置数组中。 For example: 例如:

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[];   

} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM