0

Possible Duplicate:
Efficient way to implement singleton pattern in Java

Can someone help me understand 2 ways to implement design pattern? I know one way, which is by making constructor private. Thanks for any pointers as well.

Community
  • 1
  • 1
randon
  • 95
  • 3
  • 8
  • 4
    Something smells like homework ... – zellio Jun 22 '11 at 19:22
  • 1
    It is unclear what you need that you can't find in a Google search. Please specify the problem that you are having, and why you need a second implementation. – Eric Wilson Jun 22 '11 at 19:24
  • 3
    This sums up a lot of them http://stackoverflow.com/questions/70689/efficient-way-to-implement-singleton-pattern-in-java – sealz Jun 22 '11 at 19:26
  • You need to do more than make the constructor private. The other way is with an `enum`. – mre Jun 22 '11 at 19:26
  • if you are looking for help on your homework, as @Mimisbrunnr suggests, you will need to demonstrate a real effort. – Eric Wilson Jun 22 '11 at 19:27

5 Answers5

4

The simplest implementation consists in instanciating the Singleton directly in a private field of your Singleton class:

public class Singleton {
    private static final instance = new Singleton();
    private Singleton() {}
    public Singleton getInstance() { return instance; }
}

Others implementations consist in "lazy loading" of your singleton: the instance is created only when you first call the "getInstance" method.

In order to protect your code in multi-thread context, there are various methods (double-null-check, inner class, etc.).

You will find more precisions with a quick Google search.

Benoit Courtine
  • 7,014
  • 31
  • 42
0

a simple example of Singleton design pattern is as follows:

public class SingletonPattern
{
  private static SingletonPattern instance;
  private SingletonPattern()
  { } 
public static synchronized SingletonPattern getInstance(){
  if (instance == null)
  {
    instance = new SingletonPattern();
  }
  return instance;
}

public static void main(String arg[])
  {
    System.out.println("The output of two instance:");
    SingletonPattern sp=new SingletonPattern();
    System.out.println("First Instance: "+sp.getInstance());
    sp=new SingletonPattern();
    System.out.println("Second Instance:"+sp.getInstance());
  }
}

EDIT

the other way to create Singleton Pattern is as follows:

public enum SingletonPattern
{
       INSTANCE;
       // other methods
}

enums have sole constructor and it can not be invoked by programmer, so you can not make any more instances you don’t have to worry about serialization problems as enums are serializable by default

love Computer science
  • 1,824
  • 4
  • 20
  • 39
  • @Charlie Sharma, this has already been answered by the comments above. – mre Jun 22 '11 at 19:31
  • 1
    @Charlie: How is this different from what OP said about making constructor private? – Chandu Jun 22 '11 at 19:32
  • 4
    @mre: is there a rule that i shouldn't answer it again? – love Computer science Jun 22 '11 at 19:32
  • @Charlie: OP = Original Poster – Chandu Jun 22 '11 at 19:35
  • @Charlie Sharma, there isn't a rule, but if you're that desperate for reputation, then go ahead and answer an already sufficiently answered question. – mre Jun 22 '11 at 19:38
  • @Charlie Sharma, "Is it OK now?" -- all you did was provide code to show the different ways to implement the singleton pattern. You didn't bother to explain anything. – mre Jun 22 '11 at 19:44
  • 1
    @mre: i think my answer is more explanatory than ur comment. plus this is 'Question-Answer' forum not 'Question-Comment' – love Computer science Jun 22 '11 at 19:45
  • @Charlie Sharma, And that's exactly why it's a comment. The link provided before my comment does the elaboration. Also, the justification you provided for this poor quality answer is laughable. Why don't you just take the time to provide a high quality answer, rather than saying "here you go" and providing two snippets of code? – mre Jun 22 '11 at 19:46
  • 1
    @mre: if link provided before your comment then why dont u remove your comment then? – love Computer science Jun 22 '11 at 19:57
  • @Charlie Sharma, Because I was informing OP that his statement was in fact wrong. That is, it takes more than making your constructor private to implement a singleton pattern. I'm done with you now. Too many people like you wanting rep. on this site, rather than wanting to provide quality answers. – mre Jun 22 '11 at 19:59
  • finally ur off my back!! – love Computer science Jun 22 '11 at 20:02
  • @Charlie Sharma, But not because you're right. :) – mre Jun 22 '11 at 20:04
  • 1
    woao, guys can we stop this. Thank you all for the answers. – randon Jun 22 '11 at 20:07
0

You can also use Enumeration

    public enum Foo {        
    INSTANCE;    
    } 
sealz
  • 5,348
  • 5
  • 40
  • 70
0

One simple way is to create a class with only static members. This effectively implements the singleton pattern, by never allowing multiple instances of the class.

public class Singleton {
    private static String m_string;
    private static int m_int;
    static {
        // initialization code...
    }

    public static void foo() {
    }
}

Of course, the class is not passable as an object to other methods, but this has no meaning for singletons, as they can be referred to directly from anywhere in the code (this, of course, is their biggest disadvantage, since it creates very untestable code).

Avi
  • 19,934
  • 4
  • 57
  • 70
0

Another version using the volatile keyword. I hate the volatile keyword. No sane people would bring this version to a professor because of the probable question: "What does volatile exactly do and how does it work??"

public class Singleton {

    private volatile static Singleton singleton;

    private Singleton() {}

    public static Singleton getInstance() {
        if(singleton == null) {
            synchronized (Singleton.class) {
                if(singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}
  • Yes it's thread safe.
  • Yes I check if singleton is null twice.
  • Yes it's different from Benoit's because this version lazily instantiate the singleton. The singleton is created (and the block synchronized) only if an instance is actually needed and not when the class is loaded.
  • Yes it's different from Charlie's because I synchronize only once ever. After the singleton is created I'll never synchronize again. Also, synchronizing a block instead of a method reduces the overhead.

NOTE:

  1. It might not work with older version of Java. If you're java version is old, upgrade it. If you cannot, go with Benoit's that is thread safe as well.
  2. If you're not using threads, do not synchronize because it might reduce performances by a 100 times and go with Charlie's after removing the synchronized keyword.
  3. Please no drama.
Marsellus Wallace
  • 17,991
  • 25
  • 90
  • 154