![](/img/trans.png)
[英]Single instance(singleton) of a class in a java application deployed in many nodes
[英]Single instance of Java class
我想創建一個類的單個實例。 如何在Java中創建一個類的單個實例?
要創建類的真正單個實例(暗示JVM級別的單例),您應該使您的類成為Java enum
。
public enum MyClass {
INSTANCE;
// Methods go here
}
單例模式使用靜態,因此在單元測試時通常會導致嚴重破壞。
約書亞布洛赫的Effective Java的第3項對此進行了解釋。
非常基本的單身人士。
public class Singleton {
private static Singleton instance;
static {
instance = new Singleton();
}
private Singleton() {
// hidden constructor
}
public static Singleton getInstance() {
return instance;
}
}
您也可以使用惰性持有者模式
public class Singleton {
private Singleton() {
// hidden constructor
}
private static class Holder {
static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return Holder.INSTANCE;
}
}
在訪問getInstance()之前,此版本不會創建單例實例,但由於JVM /類加載器處理內部類創建的方式,因此保證只有一次調用構造函數。
In Java, how can we have one instance of the BrokerPacket class in two threads?
這樣所有線程都會更新將不同的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[];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.