- 普通单例
- public class Singleton {
- private static Singleton uniqueInstance = new Singleton();
- private Singleton(){
- }
- public static Singleton getInstance(){
- return uniqueInstance;
- }
- }
- 文艺单例
- public class Singleton {
- private static Singleton uniqueInstance;
- private Singleton(){
- }
- public static Singleton getInstance(){
- if(uniqueInstance == null){
- synchronized (Singleton.class) {
- if(uniqueInstance == null){
- uniqueInstance = new Singleton();
- }
- }
- }
- return uniqueInstance;
- }
- }
- 2逼单例
- public class Singleton {
- private static Singleton uniqueInstance;
- private Singleton() {
- }
- public static synchronized Singleton getInstance() {
- if (uniqueInstance == null) {
- uniqueInstance = new Singleton();
- }
- return uniqueInstance;
- }
- }
最后的写法,如果在多线程环境下运行,可能会导致new多个对象,并不能保证真正的单例,
最好的写法是文艺范的,既能保证单例,又能给系统节约内存。第一个又称饿汉模式,哈哈。