设计模式_Java_多线程之单例设计模式(饿汉式和懒汉式)

单例设计模式:保证类在内存中只有一个对象。

如何保证类在内存中只有一个对象呢?

  1. 控制类的创建,不让其他类来创建本类的对象。private
  2. 在本类中定义一个本类的对象。Singleton s;
  3. 提供公共的访问方式。 public static Singleton getInstance(){return s}

单例设计模式的两种方法:
①饿汉式 开发用这种方式。
②懒汉式,单例的延迟加载模式,面试时会用到

package com.soar.thread;

public class Demo1_Singleton {
    /*
     *  单例设计模式:保证类在内存中只有一个对象。
     */
    public static void main(String[] args) {
        /*Singleton s1 = new Singleton();   //报错
        Singleton s1 = Singleton.s;         //成员变量被私有,不能通过类名.调用
        Singleton.s = null;
        Singleton s2 = Singleton.s;
        System.out.println(s1 == s2);       //true
        */

        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance();

        System.out.println(s1 == s2);       //true

        }

}

    //饿汉式 
class Singleton{
    //1.私有构造方法,其他类不能访问该构造方法了
    private Singleton(){
    }
    //2.创建本类对象
    private static Singleton s = new Singleton();
    //3.对外提供公共的访问方法
    public static Singleton getInstance(){          //获取实例
        return s;
    }
}


/*      
    //懒汉式,单例的延迟加载模式 在开发中不用,在面试的时候会用
    class Singleton{
    //1.私有构造方法,其他类不能访问该构造方法了
    private Singleton(){
    }
    //2.声明一个引用
    private static Singleton s;
    //3.对外提供公共的访问方法
    public static Singleton getInstance(){          //获取实例
        if(s == null){
            //线程1等待,线程2等待
            s = new Singleton();
        }
        return s;
    }
}*/

饿汉式和懒汉式的区别:

  1. 饿汉式是时间换空间,懒汉式是空间换时间
  2. 在多线程访问时,饿汉式不会创建多个对象,而懒汉式有可能会创建多个对象

还有一种不怎么出名的同样为单例的设计模式:

/*class Singleton{
    //1.私有构造方法,其他类不能访问该构造方法了
    private Singleton(){
    }
    //2.声明一个引用
    public  static final Singleton s = new Singleton();
}*/

举例:
Runtime类就是使用单例设计模式进行操作的

package com.soar.thread;

import java.io.IOException;

public class Demo2_Runtime {

    public static void main(String[] args) throws Exception {
        Runtime r = Runtime.getRuntime();       //获取运行时对象
        //r.exec("shutdown -s -t 3000");        //50分钟后电脑自动注销
        r.exec("shutdown -a");                  //取消刚才的操作
    }

}
posted @ 2017-09-03 09:55  Soar_Sir  阅读(139)  评论(0编辑  收藏  举报