Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Other Ways of Singleton in Java [duplicate]

Just i was thinking about the other ways of writing singleton class. So is this class considered as a singleton class?

      public class MyClass{
            static Myclass myclass;

            static { myclass = new MyClass();}

            private MyClass(){}

            public static MyClass getInstance()
            { 
                return myclass;
            }
       }

as the static block run only once.

like image 424
GuruKulki Avatar asked Jan 21 '10 18:01

GuruKulki


People also ask

Can singleton object be cloned in Java?

Cloning: Cloning is a concept to create duplicate objects. Using clone we can create copy of object. Suppose, we create clone of a singleton object, then it will create a copy that is there are two instances of a singleton class, hence the class is no more singleton.

How can we avoid cloning of singleton objects?

Prevent Singleton Pattern From Cloning To overcome the above issue, we need to implement/override the clone() method and throw an exception CloneNotSupportedException from the clone method. If anyone tries to create a clone object of Singleton , it will throw an exception, as shown in the below code.

What are the different ways to create singleton?

There are two forms of singleton design pattern, which are: Early Instantiation: The object creation takes place at the load time. Lazy Instantiation: The object creation is done according to the requirement.

How many ways we can break singleton design pattern?

There are mainly 3 concepts that can break the singleton property of a class.


2 Answers

No, it is not. You didn't declare myClass private static final, nor the getInstance() is static. The code also doesn't really compile.

Here's the Singleton idiom:

public class MyClass {
    private static final MyClass myClass = new MyClass();

    private MyClass() {}

    public static MyClass getInstance() {
        return myClass; 
    }
}

It should be private, so that nobody else can access it directly. It should be static so that there's only one of it. It should be final so that it cannot be reassigned. You also need to instantiate it directly during declaration so that you don't need to worry (that much) about threading.

If the loading is expensive and you thus rather prefer lazy loading of the Singleton, then consider the Singleton holder idiom which does initialization on demand instead of during classloading:

public class MyClass {
    private MyClass() {}

    private static class LazyHolder {
        private static final MyClass myClass = new MyClass();
    }

    public static MyClass getInstance() {
        return LazyHolder.myClass;
    }
}

You should however put big question marks whether you need a Singleton or not. Often it's not needed. Just a static variable, an enum, a factory class and/or dependency injection is often the better choice.

like image 86
BalusC Avatar answered Sep 18 '22 21:09

BalusC


Here's one more way to do it :

public enum Singleton{
  INSTANCE("xyz", 123);

  // Attributes
  private String str;
  private int i;

  // Constructor
  Singleton(String str, int i){
    this.str = str;
    this.i = i;
  }
}

According to Josh Bloch's Effective Java, this is the best way to implement Singleton in Java. Unlike implementations that involve a private static instance field, which can be multiply instantiated through the abuse of reflection and/or serialization, the enum is guaranteed to be a singleton.

The main limitation with enum singletons is that they are always instantiated at class loading time and can't be lazily instantiated. So if, for example, you want to instantiate a singleton using run-time arguments, you'll have to use a different implementation (preferably using double-checked locking).

like image 23
missingfaktor Avatar answered Sep 19 '22 21:09

missingfaktor