您的位置:首页 > 其它

单例模式--各种实现方式详解

2016-10-18 21:28 549 查看
1、饿汉模式

//饿汉模式
public class singleton1 {
private static singleton1 singleton = new singleton1();

/*
* private static singleton1 singleton;
* static{
*   singleton = new singleton1();
* }
*/

private singleton1(){

}

public static singleton1 getInstance(){
return singleton;
}

}


饿汉模式简单直接,但是有一点不好就是在初始化的时候太早了,没有做到什么时候用什么时候创建。

2、懒汉模式

//懒汉模式
public class singleton2 {
private static volatile singleton2 singleton = null;

private singleton2(){

}

public static singleton2 getInstance(){
if(singleton == null)
singleton = new singleton2();
return singleton;

}

}


懒汉模式这种实现是非线程安全的。单线程运行还可以。多线程就问题很大了。

3、Synchronized-懒汉模式

//加锁解决懒汉模式多线程不安全的问题
//synchronized 粒度有点大,加在方法上是串行的。
public class singleton3 {
private static volatile singleton3 singleton = null;

private singleton3(){

}
public synchronized static singleton3 getInstance(){
if(singleton == null)
singleton = new singleton3();
return singleton;
}

}


锁的粒度很大,java反射同样可以生成多个实例。

4、DCL-双检锁懒汉模式–避免反射的漏洞

//DCL双检锁机制实现懒汉模式的线程安全
public class singleton4 {
private static volatile singleton4 singleton = null;

private singleton4(){

}

public static singleton4 getInstance(){
if(singleton == null)
synchronized(singleton4.class){
if(singleton == null)
singleton = new singleton4();

}
return singleton;

}
}


5、使用Enum来实现单例

//枚举类型实现单例模式
public class singleton5 {

private enum singletontest{
getsingleton;
private static singletontest singleton;

private singletontest(){
}

public Connection getInstance(){
if (singleton == null){
//              singleton =传进一个比如connection的实例
}
return null;
}
}

public static Connection getinstance(){
return singletontest.getsingleton.getInstance();

}

}


6、内部类实现单例模式

public class singleton6 {

private static class singleton1{
private static singleton6 singleton = new singleton6();
}

private singleton6(){

}

public static singleton6 getInstance(){
return singleton6.singleton1.singleton;
}

}


最后这个到底是不是能够防止反射,我个人认为是可以的,因为在反射中没有考虑到内部类的情况,只考虑了方法和字段。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: