Java 设计模式之路《三》单例模式

单例模式(Singleton)

 

单例对象(Singleton)是一种常用的设计模式。在Java应用中,单例对象能保证在一个JVM中,该对象只有一个实例存在。这样的模式有几个好处:

1、某些类创建比较频繁,对于一些大型的对象,这是一笔很大的系统开销。

2、省去了new操作符,降低了系统内存的使用频率,减轻GC压力。

3、有些类如交易所的核心交易引擎,控制着交易流程,如果该类可以创建多个的话,系统完全乱了。

 

//方法一
public class Singleton {
    /* 私有构造方法,防止被实例化 */ 
    private Singleton() { 
    } 
    /* 此处使用一个内部类来维护单例 */ 
    private static class SingletonFactory { 
        private static Singleton instance = new Singleton(); 
    }
    /* 获取实例 */ 
    public static Singleton getInstance() { 
        return SingletonFactory.instance; 
    }
    /* 如果该对象被用于序列化,可以保证对象在序列化前后保持一致 */ 
    public Object readResolve() { 
        return getInstance(); 
    } 
} 
//方法二
public class Singleton {
    //将自身的实例对象设置为一个属性,并加上Static和final修饰符
    private static final Singleton instance = new Singleton();
    //将构造方法设置成私有形式
    private Singleton() {
    }
    //通过一个静态方法向外界提供这个类的实例
    public static Singleton getInstance() {
        return instance;
    }
}
//方法三
class Singleton {
    private static Singleton instance = null;
    public static Singleton getInstance() {
        if (instance == null) {
            Synchronized (instance) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance2;
    }
}

 

// 方法四
class Singleton {
    private static Singleton instance = null;
    public static synchronized Singleton getInstance() {
        if (instance == null) { 
            instance = new Singleton(); 
        } 
        return instance; 
    }
}

注:四种方法实现了一样的功能,推荐采用第一、二种方法,第三、四种方法效率低(三高于四)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值