1 min read#java
Learning Design Patterns
Some study notes and insights on learning design patterns.
Updated:
阅读中文版1. Singleton Pattern
- Eager initialization: The instance is created at the time of class initialization. It wastes some memory space but is thread-safe.
/**
* @Autor LZH
* @Date 2020/1/3 22:33
*/
public class EHan {
//Eager initialization
private static EHan instance=new EHan();
//Private constructor
private EHan(){
}
public static EHan getInstance(){
return instance;
}
}
- Lazy initialization: The instance is only checked and created when needed. There are both thread-safe and non-thread-safe implementations. The following is a thread-safe and efficient approach (double-checked locking).
public class LHan {
private LHan(){}//Private constructor
private static LHan instance=null;//Lazy initialization
public static LHan getInstance(){
if (instance==null){
synchronized(LHan.class){
if(instance==null){
instance=new LHan();
}
}
}
return instance;
}
}
Comments(0)