What is meant by Singleton Pattern?
>> Friday, May 27, 2011
SINGLETON:
One instance of a class or one value accessible globally in an application.
For example, to use a static variable to control the instance;
One instance of a class or one value accessible globally in an application.
Where to use & benefits
- Ensure unique instance by defining class final to prevent cloning.
- May be extensible by the subclass by defining subclass final.
- Make a method or a variable public or/and static.
- Access to the instance by the way you provided.
- Well control the instantiation of a class.
- Define one value shared by all instances by making it static.
- Related patterns include
For example, to use a static variable to control the instance;
class Connection {
public static boolean haveOne = false;
public Connection() throws Exception{
if (!haveOne) {
doSomething();
haveOne = true;
}else {
throw new Exception("You cannot have a second instance");
}
}
public static Connection getConnection() throws Exception{
return new Connection();
}
void doSomething() {}
//...
public static void main(String [] args) {
try {
Connection con = new Connection(); //ok
}catch(Exception e) {
System.out.println("first: " +e.getMessage());
}
try {
Connection con2 = Connection.getConnection(); //failed.
}catch(Exception e) {
System.out.println("second: " +e.getMessage());
}
}
}
0 comments:
Post a Comment