Implement singleton with static access modifier in Java

An example class with a singleton design pattern.

  class Singleton {
        private static Singleton instance;
        private int x;

        private Singleton() {
             x = 5;
        }

        public static synchronized Singleton getInstance() {
            if(instance == null) {
                instance = new Singleton();
            }
            return instance;
        }
            public void doSomething() {
                System.out.println("Hello");
        }
  }

I'm just wondering if I can create this class with the same variables and methods declared as static. Is it the same as singleton?

+4
source share
3 answers

Singleton should only be considered when all three of the following criteria are met:

  • The ownership of one copy cannot be reasonably assigned.
  • Lazy initialization is desirable
  • Global access is not intended for

Yes, this is the same.

0
source

If you really need to implement the singelton template, I would recommend using an enumeration:

public enum MySingelton{
 INSTANCE;
   private final String[] variable = new String[]{"test", "test2};
 public void randomFunction(){     
 }
}

Call the following address:

MySingelton.INSTANCE.randomFunction();

, . , .

:

Java?

http://www.drdobbs.com/jvm/creating-and-destroying-java-objects-par/208403883?pgno=3

0

singleton , , , , .

,

public class Singleton {
    private static Singleton theInstance = new Singleton();
    private int aVar = 10;
    public void aMethod() { 
        System.out.println(aVar);
    }
    public static Singleton getInstance() {
        return theInstance;
    }
}

public class FakeSingleton {
    private static int aVar = 10;
    public static void aMethod() {
        System.out.println(aVar);
    }
}

​​ ( Singleton.getInstance().aMethod() FakeSingleton.aMethod()).

, , , , :

public class Singleton {
    private static Singleton theInstance = null;
    private int aVar = 10;
    public void aMethod() { 
        System.out.println(aVar);
    }
    public static Singleton getInstance() {
        if (theInstance == null) {
            theInstance = new Singleton();
        }
        return theInstance;
    }
}

(Note that the above is not thread safe, in multi-threaded code you will need to add synchronization.)

0
source

All Articles