Problem while creating Singleton

I am trying to create a `Singleton` class, which will be accessed from two other classes.Can anyone please tell me whats wrong with the following code? I am just not able to figure out! import java.util.LinkedList; public class MessageQueue { private static final LinkedList queue = new LinkedList();; 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(); } } I am accessing the singleton object from other classes like this: MessageQueue messageQueue = MessageQueue.getInstance(); There are no errors, but System.out.println("Creating MessageQueue instance."); is getting executed whenever I do MessageQueue messageQueue = MessageQueue.getInstance(); **EDIT 1** import java.util.LinkedList; public class MessageQueue { private static final LinkedList queue = new LinkedList();; 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(); } }
What's wrong here is your first sentence: I am trying to create a Single ton class, which will be instantiated from two other classes. - you see the problem? It seems like a singleton is not what you want.

以上就是Problem while creating Singleton的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏