Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Design Pattern (JAVA) : Singleton Pattern (2)

Singleton with lazy initialization implementation:

final class Singleton {
private static Singleton s;
private static int i;
private Singleton(int x) { i = x; }
Public Static Singleton getReference() {
s = new Singleton(47);
return s;
}
public int getValue() { return i; }
public void setValue(int x) { i = x; }
}

without lazy initialization:

final class Singleton {
private static Singleton s = new Singleton(47);
private int i;
private Singleton(int x) { i = x; }
public Static Singleton getReference() {
return s;
}
public int getValue() { return i; }
public void setValue(int x) { i = x; }
}

So points to note about the singleton pattern:
1) we have to create our own private version of the constructor in order to suppress the default constructor which will be spawn by the compiler.
2) we will create a public getReference() or getInstance() method for client to access the class.
3) we will take extra caution about ensuring class members are static if we wish to implement lazy initialization.
4) we will make the class final in order to prevent client to extend this class and make it clone able accidentally.


This post first appeared on Always Remember, You Are At Most Yourself; And, Yo, please read the originial post: here

Share the post

Design Pattern (JAVA) : Singleton Pattern (2)

×

Subscribe to Always Remember, You Are At Most Yourself; And, Yo

Get updates delivered right to your inbox!

Thank you for your subscription

×