java单例面试题,Java面试题 实现单例模式

package com.coderli.interview;

/**

* 常见面试题:实现单例模式

* 《剑指offer》,第二章,面试题2

* 这里给出五种写法和对应的评论

*

* @author lihzh

* @date 2014年8月12日 上午11:10:13

*/

public class Singleton {

/**

* 写法一

* 最直接的初级写法,忽略了对多线程并发的考虑。

* 不推荐

*

* @author OneCoder

* @blog http://www.coderli.com

* @date 2014年8月12日 上午11:46:58

*/

static class SingletonOne {

// 私有化构造函数是必须的

private SingletonOne() {

}

static SingletonOne instance = null;

static SingletonOne getInstance() {

if ( instance == null) {

instance = new SingletonOne();

}

return instance;

}

}

/**

* 写法二

* 考虑到多线程并发的情况,加锁控制。

* 功能正确,但是效率不高,每次获取实例都需要先获取锁。

* 不推荐

*

* @author OneCoder

* @blog http://www.coderli.com

* @date 2014年8月12日 下午12:01:59

*/

static class SingletonTwo {

// 私有化构造函数是必须的

private SingletonTwo() {

}

static SingletonTwo instance = null;

static synchronized SingletonTwo getInstance() {

if ( instance == null) {

instance = new SingletonTwo();

}

return instance;

}

}

/**

* 写法三

* 考虑到多线程并发的情况,加锁控制。

* 同时考虑到效率问题,进行二次判断,只在需要创建新实例的时候加锁。获取的时候无锁

* 勉强过关

*

*

* @author OneCoder

* @blog http://www.coderli.com

* @date 2014年8月12日 下午12:01:59

*/

static class SingletonThree {

// 私有化构造函数是必须的

private SingletonThree() {

}

static SingletonThree instance = null;

static byte[] lock = new byte[0];

static SingletonThree getInstance() {

if ( instance == null) {

synchronized ( lock) {

if ( instance == null) {

instance = new SingletonThree();

}

}

}

return instance;

}

}

/**

* 写法四

* 考虑到多线程并发的情况,利用Java执行原理,静态方法执行一次

* 无锁,效率高

* 缺点:无论使用与否,都预先初始化完成。浪费资源。

* 推荐写法的一种

*

*

* @author OneCoder

* @blog http://www.coderli.com

* @date 2014年8月12日 下午12:01:59

*/

static class SingletonFour {

// 私有化构造函数是必须的

private SingletonFour() {

}

static SingletonFour instance = new SingletonFour();

static SingletonFour getInstance() {

return instance;

}

}

/**

* 写法四

* 考虑到多线程并发的情况,通过内部类实现按序初始化,且无锁

* 最推荐的写法

*

*

* @author OneCoder

* @blog http://www.coderli.com

* @date 2014年8月12日 下午12:01:59

*/

static class SingletonFive {

static class Inner {

static SingletonFive new_instance = new SingletonFive();

}

// 私有化构造函数是必须的

private SingletonFive() {

}

static SingletonFive getInstance() {

return Inner. new_instance;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值