Java模式

来源:互联网 发布:卷积神经网络C语言 编辑:程序博客网 时间:2024/04/30 23:59

单例模式

适用于一个类有且只有一个实例的情况。分为懒汉模式和饿汉模式:

饿汉模式:

public class Singleton{// 私有化构造方法private Singleton{}// 创建类的唯一实例,static加载private static Singleton instance = new Singleton();// 获取实例的方法,static加载public static Singleton getInstance(){return instance;}}

懒汉模式:

public class Singleton{// 私有化构造方法private Singleton{}// 声明类的唯一实例private static Singleton instance = null;// 获取实例的方法public static (synchronized) Singleton getInstance(){if(instance==null){instance = new Singleton();}return instance;}}


两种模式的比较:

饿汉模式,在加载类时已经创建对象,供线程调用。

懒汉模式,加载类时只是声明了对象,在调用实例方法的时候才真正创建实例对象。


安全问题:

在单线程操作时,当然不存在问题。

多线程并发操作时,饿汉模式是安全的。因为此时的实例对象已创建,线程只能获取同一个实例。

懒汉模式是不安全的,线程访问的不一定是同一个实例。可以通过synchronized来解决,实际开发中并不会采用。

0 0