一篇搞定设计模式之单例模式

单例模式

单例设计模式介绍

所谓类的单例设计模式,就是采取一定 的方法保证在整个软件想中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法(静态方法)。

单例模式有7种方式实现:

  • 饿汉式(静态常量)
  • 饿汉式(静态代码块)推荐
  • 懒汉式(线程不安全)
  • 懒汉式(线程不安全,线程同步方法)
  • 双重检查 推荐
  • 静态内部类 推荐
  • 枚举
饿汉式(静态常量)

饿汉式(静态常量)应用实例

步骤:

  1. 构造器私有化(防止new)
  2. 类的内部创建对象
  3. 向外暴露一个静态的公共方法

代码实现:

public class SingletonTest01 {

    public static void main(String[] args) {
        //获取两个Singleton对象
        Singleton singleton1 = Singleton.getSingleton();
        Singleton singleton2 = Singleton.getSingleton();
        //输出true, 证明两次获取到的对象都是相同的
        System.out.println(singleton1 == singleton2);
        System.out.println("singleton1.hashCode() = " + singleton1.hashCode());
        System.out.println("singleton1.hashCode() = " + singleton2.hashCode());
    }
}

class Singleton{
    //1. 本类内部创建对象实例
    private static final Singleton instance = new Singleton();
    //2. 构造器私有化,不给外部new
    private Singleton(){}
    //3. 提供一个共有的静态方法,返回实例对象
    public static Singleton getSingleton(){
        return instance;
    }
}
饿汉式(静态代码块)

优缺点说明:

  • 优点:这种写法很简单,就是在类装载的时候就完成实例化。避免了线程同步问题
  • 缺点:在类装载的时就完成实例化,没有达到懒加载(Lazy Loading)的效果。如果从始至终从未使用过这个实例,则会造成内存的浪费
  • 总结: 这种单例模式可以用,前提是必须保证这个类被使用至少一次,不然会造成内存的浪费。

饿汉式(静态代码块)应用案例

public class SingletonTest02 {

    public static void main(String[] args) {
        //获取两个Singleton对象
        Singleton02 singleton1 = Singleton02.getSingleton02();
        Singleton02 singleton2 = Singleton02.getSingleton02();
        //输出true, 证明两次获取到的对象都是相同的
        System.out.println(singleton1 == singleton2);
        System.out.println("singleton1.hashCode() = " + singleton1.hashCode());
        System.out.println("singleton1.hashCode() = " + singleton2.hashCode());
    }
}

class Singleton02 {

    private static Singleton02 instance;

    private Singleton02(){}

    static {    //在静态代码块中,创建单例对象
        instance = new Singleton02();
    }

    public static Singleton02 getSingleton02(){
        return instance;
    }
}
懒汉式(线程不安全)

缺点说明:

  • 如果在多线程开发中使用这种方法会造成线程不安全
  • 原因:如果A线程进入到if时,被B线程抢到线程执行权则B会创建一个对象,A回来执行也会创建一个对象
  • 总结:在实际开发中,不推荐使用懒汉式单例模式

懒汉式(线程不安全)应用实例:

public class SingletonTest03 {
    public static void main(String[] args) {
        //获取两个Singleton对象
        Singleton singleton1 = Singleton.getInstance();
        Singleton singleton2 = Singleton.getInstance();
        //输出true, 证明两次获取到的对象都是相同的
        System.out.println(singleton1 == singleton2);
        System.out.println("singleton1.hashCode() = " + singleton1.hashCode());
        System.out.println("singleton1.hashCode() = " + singleton2.hashCode());
    }
}

class Singleton{

    private static Singleton instance;

    private Singleton(){}

    public static Singleton getInstance(){
        if(instance == null){
            instance = new Singleton();
        }
        return instance;
    }
}
懒汉式(线程安全、同步代码块)

优缺点说明:

  • 优点:线程安全、实现了懒加载的效果
  • 缺点:用多线程时,有多个线程都想拿得到这个对象,而每一次都需要等待上一个线程
  • 总结:实际开发中,不推荐使用这种方式

懒汉式(线程安全、同步代码块)应用实例:

public class SingletonTest04 {
    public static void main(String[] args) {
        //获取两个Singleton对象
        Singleton04 singleton1 = Singleton04.getInstance();
        Singleton04 singleton2 = Singleton04.getInstance();
        //输出true, 证明两次获取到的对象都是相同的
        System.out.println(singleton1 == singleton2);
        System.out.println("singleton1.hashCode() = " + singleton1.hashCode());
        System.out.println("singleton1.hashCode() = " + singleton2.hashCode());
    }
}

class Singleton04{

    private static Singleton04 instance;

    private Singleton04(){}

    /**
     * 加入同步处理的代码,解决线程安全问题
     * 但是效率变低了
     * @return
     */
    public static synchronized Singleton04 getInstance(){
        if(instance == null){
            instance = new Singleton04();
        }
        return instance;
    }
}
双重检查

优点说明:

  • 这种方式是开发中经常用到的,如下代码中,进行了两次 if 的检查,这样就可以保证线程安全了
  • 优点:线程安全、延迟加载(懒加载)、效率较高
  • 结论:在实际开发中,推荐使用这种单例设计

双重检查应用实例:

public class SingletonTest05 {
    public static void main(String[] args) {
        //获取两个Singleton对象
        Singleton singleton1 = Singleton.getInstance();
        Singleton singleton2 = Singleton.getInstance();
        //输出true, 证明两次获取到的对象都是相同的
        System.out.println(singleton1 == singleton2);
        System.out.println("singleton1.hashCode() = " + singleton1.hashCode());
        System.out.println("singleton1.hashCode() = " + singleton2.hashCode());
    }
}

class Singleton{

    private static volatile Singleton instance;

    private Singleton(){}

    /**
     * 加入双重检查代码,解决线程问题,同时解决懒加载问题
     * 同时保证了效率
     * @return
     */
    public static Singleton getInstance(){
        if(instance == null){
            synchronized (Singleton.class) {
                if(instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
静态内部类

优点说明:

  • 这种方式采用了类装咋子的机制来保证初始化实例时只有一个线程。
  • 静态内部类方式在Singleton类被加载时并不会立即实例化,而是需要实例化时,调用getInstance方法,才会装载SingletonInstance类,从而完成Singleton的实例化
  • 类打的静态属性只会在第一次加载类的时候初始化,所以在这里,JVM帮助我们保证了线程的安全性,在类进行初始化时,别的线程是无法进入的
  • 优点:避免了线程不安全,利用静态内部类特点实现延迟加载,效率高
  • 结论:推荐使用

静态内部类 应用实例:

public class SingletonTest06 {
    public static void main(String[] args) {
        //获取两个Singleton对象
        Singleton singleton1 = Singleton.getInstance();
        Singleton singleton2 = Singleton.getInstance();
        //输出true, 证明两次获取到的对象都是相同的
        System.out.println(singleton1 == singleton2);
        System.out.println("singleton1.hashCode() = " + singleton1.hashCode());
        System.out.println("singleton1.hashCode() = " + singleton2.hashCode());
    }
}

class Singleton{

    private Singleton(){}
	//写一个静态内部类,该类中有一个静态属性 Singleton
    private static class SingletonInstance{
        private final static Singleton INSTANCE = new Singleton();
    }
	//提供一个获取共有方法,直接返回SingletonInstance.INSTANCE
    public static Singleton getInstance(){
        return SingletonInstance.INSTANCE;
    }
}
枚举

优缺点说明:

  • 借助JDK1.5添加的枚举来实现单例模式,不仅能避免线程同步问题,而且还能防止反序列化重新创建新的对象
  • 总结: 推荐使用

枚举应用实例:

public class SingletonTest07 {
    public static void main(String[] args) {
        Singleton instance1 = Singleton.INSTANCE;
        Singleton instance2 = Singleton.INSTANCE;
        System.out.println(instance1 == instance2);
        System.out.println(instance1.hashCode());
        System.out.println(instance2.hashCode());
        instance1.test();
    }
}

enum Singleton{
    INSTANCE;	//属性
    public void test(){	//方法
        System.out.println("ok");
    }
}

单例模式在JDK应用的源码分析

在**Java.lang包下的Runtime使用了饿汉式(静态常量)**的单例模式

代码:

public class Runtime {
    private static Runtime currentRuntime = new Runtime();

    /**
     * Returns the runtime object associated with the current Java application.
     * Most of the methods of class <code>Runtime</code> are instance
     * methods and must be invoked with respect to the current runtime object.
     *
     * @return  the <code>Runtime</code> object associated with the current
     *          Java application.
     * 		
     */
    public static Runtime getRuntime() {
        return currentRuntime;
    }
    /** Don't let anyone else instantiate this class */ 
    private Runtime() {}
    //很有很多的方法.......
}

单例模式注意事项和细节说明

  • 单例模式保证了系统内存中该类只存在一个对象,节省了系统资源,对于一些需要频繁创建销毁的对象,使用单例模式可以提高系统性能
  • 当想实例化一个单例类的时候,必须要记住使用相应的获取对象的方法,而不是使用new
  • 单例模式使用场景:需要频繁的进行创建和销毁的对象、创建对象时耗时过多或耗费资源过多(即:重量级对象),但又经常使用到的对象、工具类对象频繁访问数据库文件的对象(比如数据源、session工厂等)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hello,Anton

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值