我正在尝试创建一个Singleton
类,可以从其他两个类访问。任何人都可以告诉我以下代码有什么问题?我只是无法搞清楚!
import java.util.LinkedList;
public class MessageQueue {
private static final LinkedList<ServerDataEvent> queue = new LinkedList<ServerDataEvent>();;
private static MessageQueue messageQueue = null;
/** A private Constructor prevents any other class from instantiating. */
private MessageQueue() {
}
/** Static 'instance' method */
public static MessageQueue getInstance() {
if (MessageQueue.messageQueue == null) {
System.out.println("Creating MessageQueue instance.");
MessageQueue.messageQueue = new MessageQueue();
}
return MessageQueue.messageQueue;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
我从其他类中访问单例对象:
MessageQueue messageQueue = MessageQueue.getInstance();
没有错误,但
System.out.println("Creating MessageQueue instance.");
每当我做时,就会被执行
MessageQueue messageQueue = MessageQueue.getInstance();
编辑1
import java.util.LinkedList;
public class MessageQueue {
private static final LinkedList<ServerDataEvent> queue = new LinkedList<ServerDataEvent>();;
private static final MessageQueue messageQueue = new MessageQueue();
/** A private Constructor prevents any other class from instantiating. */
private MessageQueue() {
System.out.println("problem...");
}
/** Static 'instance' method */
public static MessageQueue getInstance() {
return MessageQueue.messageQueue;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
答案 0 :(得分:4)
首先,您没有指定任何错误。如果您想获得帮助,您应该尽可能多地向我们提供信息。
其次,在Java中创建单例的最好的万无一失的方法是:
public enum MySingleton {
INSTANCE;
//whatever methods you want to implement
}
您可以像这样访问它:MySingleton.INSTANCE.whatever()
。
答案 1 :(得分:3)
定义和实例化你的单例对象要好得多:
private static final MessageQueue messageQueue = new MessageQueue();
然后getInstance
将只是:
public static MessageQueue getInstance() {
return MessageQueue.messageQueue;
}
这样就可以实例化你的单例对象,并且它是线程安全的,因为它是由类加载器创建的。
答案 2 :(得分:1)
一个线程安全的较短版本。
public enum MessageQueue {
INSTANCE;
private final Queue<ServerDataEvent> queue =
new ConcurrentLinkedQueue<ServerDataEvent>();
public void addEvent(ServerDataEvent event) { queue.add(event); }
}
或
public enum MessageQueue {
;
private static final Queue<ServerDataEvent> queue =
new ConcurrentLinkedQueue<ServerDataEvent>();
public static void addEvent(ServerDataEvent event) { queue.add(event); }
}
答案 3 :(得分:0)
public class MessageQueue {
private static final MessageQueue INSTANCE= new MessageQueue();
public static MessageQueue getINSTANCE() {
return INSTANCE;
}
private MessageQueue() {
}
}
答案 4 :(得分:0)
发生了什么错误?我从中可以看出,你在这里有两个分号:
private static final LinkedList<ServerDataEvent> queue = new LinkedList<ServerDataEvent>();;
答案 5 :(得分:0)
最简单的方法:
private static final MessageQueue messageQueue = new MessageQueue();
public static MessageQueue getInstance() {
return MessageQueue.messageQueue;
}