One of the patterns described is singleton. This is a popular pattern in java. So, how could you develop it java?
class Singleton{
private static Singleton singleton;
private Singleton{}
public static synchronized Singleton getInstance() {
if (instance == null) instance = new Singleton();
return instance;
}
}
But, how about this?
public enum Singleton{
INSTANCE;
public void yourBusinessMethod(){}
}
A single-element enum type is the best way to implement a singleton. This is stated in "Effective Java".
What are the pros of this solution?
- no serialization problems
- guarantee against multiple instantiation
- easy to read (less) code
Комментариев нет:
Отправить комментарий