Java Singleton Pattern

后端 未结 8 1800
难免孤独
难免孤独 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 05:48

    since getInstance() method is "static" and instance field too, yo can use Singleton.getInstance(); Without creating new exeple of class. Thihs is the poit of singletone

    0 讨论(0)
  • 2020-12-03 05:54
    Singleton singleton = Singleton.getInstance();
    

    is the correct way. Make sure your getInstance() method is indeed static.

    Since your Singleton implementation is far from being safe - your object can be instantiated via reflection, you may want to create a singleton based on enum

    0 讨论(0)
  • 2020-12-03 05:58

    It is still possible to create more than one instance of the class, as follows:

    Singleton.getInstance().clone()
    
    0 讨论(0)
  • 2020-12-03 05:59

    This one:

     Singleton singleton = Singleton.getInstance();
    

    should work. This is how you call static methods in Java. And the getInstance() method is declared as static. Are you sure you are using the very same Singleton class? Or maybe you have imported a class called the same in some other package.

    0 讨论(0)
  • 2020-12-03 06:00

    Since we doesn't want to allow more than one copy to be accessed. So We need to manually instantiate an object, but we need to keep a reference to the singleton so that subsequent calls to the accessor method can return the singleton (rather than creating a new one). Thats why is

    Singleton singleton = Singleton.getInstance();
    

    Correct way to access any singletonObject.

    0 讨论(0)
  • 2020-12-03 06:01

    There is nothing wrong in using

    Singleton singleton = Singleton.getInstance();
    // error - non-static method cannot be referenced from a static context
    

    This is the way to get the singleton object form the class. There must me something else. Please post some more details

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