码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式

时间:2018-02-27 21:20:39      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:zed   实例化   one   它的   ==   static   进入   单例模式   turn   

单例类全局唯一,无论是哪个方法调用单例类,它的实例化就只是那一个,不会改变

以下为几种单例模式:
1、懒汉(非线程安全)
/***
* 懒汉,非线程安全
*/
public class SingletoneTest {
private static SingletoneTest instance;

private SingletoneTest() {
}


public static SingletoneTest getInstance() {
if (instance == null) {
instance = new SingletoneTest();
}
return instance;
}
}
2、懒汉,线程安全
/***
* 懒汉,线程安全
*/
public class SingletoneTest {
private static SingletoneTest instance;

private SingletoneTest(){}


public static synchronized SingletoneTest getInstance(){
if(instance == null){
instance = new SingletoneTest();
}
return instance;
}
}
这种线程安全的懒加载有一个问题,就是如果我没有实例化,进入synchronized方法中是没有问题,但是如果我已经实例化了,仍然是要进入synchronized方法中,这样的性能有点问题

3、懒汉,线程安全,变种
/***
* 懒汉,线程安全,变种
*/
public class SingletoneTest {
private static SingletoneTest instance;

private SingletoneTest(){}

public static SingletoneTest getInstance(){
if(instance == null){
synchronized (instance){
if (instance == null){
instance = new SingletoneTest();
}
}
}
return instance;
}
}
4、饿汉

/***
* 饿汉
*/
public class SingletoneTest {
private static SingletoneTest instance = new SingletoneTest();

private SingletoneTest(){}

public static SingletoneTest getInstance(){
return instance;
}
}

5、饿汉变种
/***
* 饿汉,变种
*/
public class SingletoneTest {
private static SingletoneTest instance = null;

static {
instance = new SingletoneTest();
}
private SingletoneTest(){}

public static SingletoneTest getInstance(){
return instance;
}
}
这种和一般的饿汉模式看起来挺像,但是其实都是一样的,都是在初始化的时候就将对象实例化了

6、使用静态内部类
/***
* 使用静态内部类
*/
public class SingletoneTest {
private static class SingletoneHoder{
private static final SingletoneTest instance = new SingletoneTest();
};

private SingletoneTest(){}

public static final SingletoneTest getInstance(){
return SingletoneHoder.instance;
}
}

单例模式

标签:zed   实例化   one   它的   ==   static   进入   单例模式   turn   

原文地址:https://www.cnblogs.com/zmjBlog/p/8480369.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!