设计模式随笔:单例模式
Posted chylcblog
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式随笔:单例模式相关的知识,希望对你有一定的参考价值。
单例模式一般分为:懒汉、饿汉、双重校验锁、枚举、静态内部类五种。
懒汉:
第一次调用时,创建对象
public class Single { private static Single instance; private Single(){}; public static Single getInstance() { if (instance == null) { instance = new Single(); } return instance; } }
饿汉:
public class Single { private static Single instance = new Single(); private Single(){}; public static Single getInstance() { return instance ; } }
双重校验锁:
public class Single { private volatile static Single singleton; //1:volatile修饰 private Single(){} public static Single getSingleton() { if (singleton == null) { synchronized (Single.class) { if (singleton == null) { singleton = new Single(); } } } return singleton; } }
静态内部类:
public class Single { private Single() {} public static Single getInstance() { return Inner.instance; } public static class Inner { private static final Single instance = new Single(); } }
枚举:
public enum Singleton { INSTANCE; public void whateverMethod() { } }
以上是关于设计模式随笔:单例模式的主要内容,如果未能解决你的问题,请参考以下文章