邢台网站开发公司,湖北百度关键词排名软件,去长沙旅游攻略及费用,储煤棚网架公司转载自 设计模式之单例模式实践概念单例模式即一个JVM内存中只存在一个类的对象实例分类1、懒汉式
类加载的时候就创建实例
2、饿汉式
使用的时候才创建实例当然还有其他的生成单例的方式#xff0c;双重校验锁#xff0c;枚举和静态内部类#xff0c;文中会有介绍实践懒汉式…转载自 设计模式之单例模式实践概念单例模式即一个JVM内存中只存在一个类的对象实例分类1、懒汉式
类加载的时候就创建实例
2、饿汉式
使用的时候才创建实例当然还有其他的生成单例的方式双重校验锁枚举和静态内部类文中会有介绍实践懒汉式
1)线程不安全不可用
public class Singleton { private static Singleton instance; private Singleton (){} public static Singleton getInstance() { if (instance null) { instance new Singleton(); } return instance; }
} 2)线程安全同步方法效率低不推荐
public class Singleton { private static Singleton instance; private Singleton (){} public static synchronized Singleton getInstance() { if (instance null) { instance new Singleton(); } return instance; }
} 3)线程不安全会产生多个实例不可用
public class Singleton {private static Singleton singleton;private Singleton() {}public static Singleton getInstance() {if (singleton null) {synchronized (Singleton.class) {singleton new Singleton();}}return singleton;}
}饿汉式无线程安全问题不能延迟加载影响系统性能
4)
public class Singleton { private static Singleton instance new Singleton(); private Singleton (){} public static Singleton getInstance() { return instance; }
} 5)
public class Singleton { private static Singleton instance null; static { instance new Singleton(); } private Singleton (){} public static Singleton getInstance() { return instance; }
}6)双重校验锁线程安全推荐使用
public class Singleton {private static volatile Singleton singleton;private Singleton() {}public static Singleton getInstance() {if (singleton null) {synchronized (Singleton.class) {if (singleton null) {singleton new Singleton();}}}return singleton;}
} 7)静态内部类线程安全主动调用时才实例化延迟加载效率高推荐使用
public class Singleton { private static class SingletonHolder { private static final Singleton INSTANCE new Singleton(); } private Singleton (){} public static final Singleton getInstance() { return SingletonHolder.INSTANCE; }
} 8)枚举类型无线程安全问题避免反序列华创建新的实例很少使用
public enum Singleton { INSTANCE; public void whateverMethod() { }
}注意事项1、考虑多线程问题
2、单例类构造方法要设置为private类型禁止外界new创建
private Singleton() {}
3、如果类可序列化考虑反序列化生成多个实例问题解决方案如下
private Object readResolve() throws ObjectStreamException { // instead of the object were on, return the class variable INSTANCE return INSTANCE;
} 使用场景1、工具类对象
2、系统中只能存在一个实例的类
3、创建频繁或又耗时耗资源且又经常用到的对象下面是单例模式在JDK的应用另外spring容器中的实例默认是单例饿汉式类型的即容器启动时就实例化bean到容器中当然也可以设置懒汉式defalut-lazy-inittrue为延迟实例化用到时再实例化。