Java Singleton Pattern

后端 未结 8 1801
难免孤独
难免孤独 2020-12-03 05:22

Edit: Answered - error was method wasn\'t static

I\'m used the Singleton Design Pattern

 public class Singleton {
   private static final Singleton I         


        
相关标签:
8条回答
  • 2020-12-03 06:08

    Singleton singleton = Singleton.getInstance(); should work -- that error doesn't make sense, given your code; are you sure you're reporting it correctly? (It would make sense if you had forgotten to make the getInstance method static, which you've done in your code above.)

    The code you've given us for the class is correct.

    Lastly, one conceptual note: First, you aren't "creating an object of class Singleton" -- that's the whole point of a Singleton. :) You're just getting a reference to the existing object.

    0 讨论(0)
  • 2020-12-03 06:09
    1. since the constructor is private, it does not make sense to create an object using the constructor.
    2. you should be using public static Singleton getInstance(), but the implementation is not very correct.

      if (instance == null) {
      instance = new Singleton();
      }
      return instance;

    This is how you should be doing it. This ensure that it creates the instance if it does not exist, or simply returns the existing instance. Your code would also do the same thing, but this add to the readability.

    0 讨论(0)
提交回复
热议问题