开发者

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?


To create a truly single instance of your class (implying a singleton at the JVM level), you should make your class a 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.


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.


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

} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜