java4all@1986 java. Powered by Blogger.

What is meant by singlepattern Design and example?

>> Monday, May 23, 2011

Singleton Pattern:

Singleton provides a global access point
A singleton often has the characteristics of a registry or lookup service.
A singleton prevents the client programmer from having any way to create an object except the ways you provide.
You must make all constructors private.
You must create at least one constructor to prevent the compiler from synthesizing a default constructor.
You provide access through public methods.
Making the class final prevents cloning.



Take a final class:

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;
}
}
public class SingletonPattern {

public static void main(String[] args) {
Singleton s = Singleton.getReference();
String result = "" + s.getValue();
System.out.println(result);
Singleton s2 = Singleton.getReference();
s2.setValue(9);
result = "" + s.getValue();
System.out.println(result);
}
}

0 comments:

Post a Comment

FaceBook Login

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

Total Pageviews

STATCOUNTER

  © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

Back to TOP