0

Creation of Singleton class in Java has been discussed and debated in various communities multiple times. Even after all the discussions, the debaters aren't satisfied with array of provided solutions.

My question is simply to find out the best & most effective way to create any class Singleton in Java & C++.

Callum Rogers
  • 15,630
  • 17
  • 67
  • 90
user3374518
  • 1,359
  • 3
  • 11
  • 11
  • See also all related links on right, ["singleton c++"](https://www.google.com/search?q=singleton+c%2B%2B) and ["singleton java"](https://www.google.com/search?q=singleton+java). – Jason C Mar 21 '14 at 09:27

2 Answers2

2

Simple Answer: Use enum.

public enum SimplySingleton { 
    INSTANCE; 
    public void doSomethingSimple() {
        // Do something simple.
    }
}

Detailed Answer:

The Singleton design pattern addresses all of these concerns. With the Singleton design pattern you can:

  • Ensure that only one instance of a class is created.
  • Provide a global point of access to the object.
  • Allow multiple instances in the future without affecting a singleton class's clients.

According to Effective Java Reloaded, the most effective & right way to implement a serialization singleton class is to use an enum to maintain the instance.

Below is the code which explains how to use the above defined enum SimplySingleton.

public enum Magic {
       INSTANCE;
       private final String fooString = "Best way to implement Singleton";
       public void doSingletonMagic() {
           Magic.INSTANCE.doSomethingSimple();
           System.out.println(fooString);
       }
}

Enum provide implicit support for thread safety and only one instance is guaranteed. This is also a good way to have singleton with minimum effort.

Hope this helps you.

Shishir

Shishir Kumar
  • 7,981
  • 3
  • 29
  • 45
2

Leaving aside any discussions on the merits of the singleton or lack thereof, this is a simple implementation whose instantiation is thread-safe in C++11:

class Foo
{
 public:
  static Foo& instance()
  {
     static Foo f;
     return f;
  }

 private:
  Foo() {}
  Foo(const Foo&) = delete;           // not copyable or move-copyable
  Foo& operator(const Foo&) = delete; // not assignable or move-assignable
};

This is how one would access an instance:

Foo& f = Foo::instance();
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • Would be nice to add a usage for people not knowledgeable with C++ ;) – fge Mar 21 '14 at 09:28
  • 1
    @fge OK, done, although I am not a big fan of singletons, so my usage advice would be "don't use it unless you are absolutely certain there is no alternative". – juanchopanza Mar 21 '14 at 09:30
  • I can understand that, but opinions remain opinions :p Thanks! – fge Mar 21 '14 at 09:37