您的位置:首页 > 编程语言 > Java开发

实现单例模式的五种方法

2015-06-06 20:22 459 查看

当提到设计模式时,一般都会想到的单例,很多人都知道单例模式分为懒汉式和饿汉式,单例的作用是:保证一个类的实例有且只有一个,从这点来看实际上实际上实现单例模式就不止上面两种了。下面来分析分析:

一、饿汉式:

public class Singleton {

    //1、将构造方法私有化,不允许外部直接创建对象

    private Singleton(){

    }

    //2、创建类的唯一实例,使用private static修饰

   private static Singleton instance = new Singleton();

   //3、提供一个用于获取实例的方法,使用public static修饰

   public static  Singleton getIntance(){

       return instance;

   }

}

二、懒汉式

public class Singleton2 {

    //1、将构造方法私有化,不允许外边直接创建对象

    private Singleton2(){

    }

    //2、声明类的唯一实例,使用private static修饰

    private static  Singleton2 instance;

    //3、提供一个用于获取实例的方法,使用public static修饰

    public static synchronized Singleton2 getIntance(){
if(instance==null){
  instance = new Singleton2();
}
return instance;

    }

懒汉式与饿汉式的区别:
饿汉模式的特点是加载类时比较慢,但运行时获取对象的速度比较快;线程安全
懒汉模式的特点是加载类时比较快,但运行时获取对象的速度比较慢;线程不安全

三、第三种也叫双重锁检测
这个模式将同步内容放到if内部,提高了执行的效率,不必每次获取对象时都进行同步,只有第一次同步。
这中方式也有一定的问题:由于编译器优化原因和JVM底层内部模型原因,偶尔可能会出问题。
代码:
public class Singleton3{
private static Singleton3 instance = null;
public static Sington3 getInstance(){
if(instance == null){
Singleton3 sc;
synchronized(Singleton3.class){
sc = instance;
if(sc == null){
synchronized(Singleton3.class){
if(sc ==null){
sc = new Singleton3();
}
}
instance = sc;
}
}

}
return instance;
}
private Singleton3(){}
}
四、静态内部类
public class Singleton4 {

    SingletonDemo s = SingletonDemo.getInstance();

   private static class  SingletonDemo{
private SingletonDemo() {
}
private static final SingletonDemo instance = new SingletonDemo();
public static SingletonDemo getInstance(){
   return SingletonDemo.instance;
}

    }

}

这种方法由于外部类没有static属性,则不会像饿汉式那样立即加载对象,只有真正调用getInstance(),才会加载静态内部类,加载时线程安全的。
优势是并发搞笑调用和延迟加载。
五、用枚举实现单例模式
枚举本身就是单例模式,由JVM从根本上提供保障,但是无法延迟加载
public enum Singleton5 {

    INSTANCE;

    public void SingletonOperator(){
//相关操作

    }

}

以上就是单例的五种实现方式。
除过第三种:其它四种比较可以发现:

占用资源少,不需要延时加载:枚举好于饿汉

占用资源大,需要延时加载:静态好于懒汉。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息