Singleton模式是什么,这里不解释,直接上代码。这里分享了5种写法,并附上了评论。有好有坏,大家自行理解。
/** * 常见面试题:实现单例模式
public class Singleton {
/** * 写法一 <br> * 最直接的初级写法,忽略了对多线程并发的考虑。
* 不推荐 * *
static class SingletonOne {
// 私有化构造函数是必须的
private SingletonOne() {
}
static SingletonOne instance = null;
static SingletonOne getInstance() {
if ( instance == null) {
instance = new SingletonOne();
}
return instance;
}
}
/**
* 写法二
* 考虑到多线程并发的情况,加锁控制。
* 功能正确,但是效率不高,每次获取实例都需要先获取锁。
* 不推荐
*/
static class SingletonTwo {
// 私有化构造函数是必须的
private SingletonTwo() {
}
static SingletonTwo instance = null;
static synchronized SingletonTwo getInstance() {
if ( instance == null) {
instance = new SingletonTwo();
}
return instance;
}
}
/**
* 写法三 <br>
* 考虑到多线程并发的情况,加锁控制。 <br>
* 同时考虑到效率问题,进行二次判断,只在需要创建新实例的时候加锁。获取的时候无锁 <br>
* 勉强过关
*/
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;
}
}
/**
* 写法四 <br>
* 考虑到多线程并发的情况,利用Java执行原理,静态方法执行一次 <br>
* 无锁,效率高 <br>
* 缺点:无论使用与否,都预先初始化完成。浪费资源。 <br>
* 推荐写法的一种
*/
static class SingletonFour {
// 私有化构造函数是必须的
private SingletonFour() {
}
static SingletonFour instance = new SingletonFour();
static SingletonFour getInstance() {
return instance;
}
}
/**
* 写法四 <br>
* 考虑到多线程并发的情况,通过内部类实现按序初始化,且无锁 <br>
* 最推荐的写法
*/
static class SingletonFive {
static class Inner {
static SingletonFive new_instance = new SingletonFive();
}
// 私有化构造函数是必须的
private SingletonFive() {
}
static SingletonFive getInstance() {
return Inner. new_instance;
}
}
}