Implement a Singleton
Page 1 of 1
Implement a Singleton
1. Define a private static attribute in the “single instance” class.
2. Define a public static accessor function in the class.
3. Do “lazy initialization” (creation on first use) in the accessor function.
4. Define all constructors to be protected or private.
5. Clients may only use the accessor function to manipulate the Singleton.
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
// Private constructor prevents instantiation from other classes
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
2. Define a public static accessor function in the class.
3. Do “lazy initialization” (creation on first use) in the accessor function.
4. Define all constructors to be protected or private.
5. Clients may only use the accessor function to manipulate the Singleton.
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
// Private constructor prevents instantiation from other classes
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
Similar topics
» How can we make a class Singleton?
» [C] Implement strcpy function
» Write a method to implement *,-,/ operations. You should use only the + operator
» Choose data structure to implement insert, get median
» [C] Implement strcpy function
» Write a method to implement *,-,/ operations. You should use only the + operator
» Choose data structure to implement insert, get median
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum
|
|