> 最近重新学习了一下单例模式,写博客总结一下,有错误或者另外的方法欢迎指出
单例模式的六种常见形式
一、饿汉式:直接创建对象,无线程安全问题
1.1直接实例化饿汉式(简洁直观)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| package com.lp.singleton;
public class HungrySingleton1 { public static final HungrySingleton1 INSTANCE=new HungrySingleton1(); private HungrySingleton1(){} }
|
1.2枚举式(最简洁)
1 2 3 4 5 6 7 8 9 10 11 12
| package com.lp.singleton;
public enum HungrySingleton2{ INSTANCE }
|
1.3静态代码块饿汉式(适合复杂饿汉式)
1 2 3 4 5 6 7 8 9 10 11 12 13
| package com.lp.singleton;
public class HungrySingleton3 { public static final HungrySingleton3 INSTANCE; static { INSTANCE=new HungrySingleton3(); } private HungrySingleton3(){} }
|
二、懒汉式:延迟创建对象
2.1线程不安全(适用于单线程)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| package com.lp.singleton;
public class lazySingleton1 { private static lazySingleton1 instance;
private lazySingleton1() { }
public static lazySingleton1 getInstance() { if (instance == null) { instance = new lazySingleton1(); } return instance; } }
|
2.2线程安全(适用于多线程)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| package com.lp.singleton;
public class lazySingleton2 { private static lazySingleton2 instance;
private lazySingleton2() { }
public static lazySingleton2 getInstance() { if(instance == null) { synchronized (lazySingleton2.class) { if (instance == null) { instance = new lazySingleton2(); } } } return instance; } }
|
2.3静态内部类(适用于多线程)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| package com.lp.singleton;
public class lazySingleton3 {
private lazySingleton3() { }
private static class Inner { public static final lazySingleton3 INSTANCE=new lazySingleton3(); } public static lazySingleton3 getInstance(){ return Inner.INSTANCE; } }
|