饿汉式单例模式
// 饿汉式单例public class Hungry {// 可能会浪费空间private Hungry(){}private final static Hungry HUNGRY = new Hungry();public static Hungry getInstance(){return HUNGRY;}}
这种方式实现的很简单,用很明显的延迟初始化但是线程不安全不支持多线程访问,严格来说并不是一个单例模式
线程安全的饿汉单例模式
import com.sun.corba.se.impl.orbutil.CorbaResourceUtil;import java.lang.reflect.Constructor;import java.lang.reflect.Field;// 懒汉式单例// 道高一尺,魔高一丈!public class LazyMan {private static boolean qinjiang = false;private LazyMan(){synchronized (LazyMan.class){if (qinjiang == false){qinjiang = true;}else {throw new RuntimeException("不要试图使用反射破坏异常");}}} private volatile static LazyMan lazyMan;// 双重检测锁模式的 懒汉式单例 DCL懒汉式public static LazyMan getInstance(){if (lazyMan==null){synchronized (LazyMan.class){if (lazyMan==null){lazyMan = new LazyMan(); // 不是一个原子性操作}}}return lazyMan;}// 反射!public static void main(String[] args) throws Exception {// LazyMan instance = LazyMan.getInstance();Field qinjiang = LazyMan.class.getDeclaredField("qinjiang");qinjiang.setAccessible(true);Constructor<LazyMan> declaredConstructor =LazyMan.class.getDeclaredConstructor(null);declaredConstructor.setAccessible(true);LazyMan instance = declaredConstructor.newInstance();qinjiang.set(instance,false);LazyMan instance2 = declaredConstructor.newInstance();System.out.println(instance);System.out.println(instance2);}}
静态内部类实现单例模式
public class person{private person(){}public static person getinstance(){}public static class per(){private final static person person=new person();}}
使用枚举来实现单例模式
代码块
