美文网首页
单例模式

单例模式

作者: wuhuaguo丶 | 来源:发表于2019-06-13 17:19 被阅读0次

    单例模式:jdk中的getRuntime();
    工厂方法模式:ThreadPoolExcutor用到ThreadFactory;
    观察者模式:java.util包下面的Observable和Observer;
    代理模式: Spring中AOP的实现

    单例模式的几种实现方式:

    Java单例模式的不同写法(懒汉式、饿汉式、双检锁、静态内部类、枚举)

    1. 饿汉式
    2. 懒汉式
    3. 双重校验锁
      public class Singleton {
      private static volatile Singleton instance = null;
      private Singleton(){}
      public static Singleton getInstance() {
          if (instance == null) {   // Single Checked
              synchronized (Singleton.class) {
                  if (instance == null) { // Double checked
                      instance = new Singleton();
                  }
              }
          }
          return instance;
      }
      }
      
    4. 静态内部类
      public class Singleton{
      // 使用一个静态类(SingletonHolder)来创建Singleton,其他静态方法只要没有调用SingletonHolder.instance就不会创建Singleton
      // 实现了需要时才创建实例对象,避免过早创建
      private static class SingletonHolder{
          public static Singleton instance = new Singleton();
      }
      private Singleton(){}
      public static Singleton newInstance(){
          return SingletonHolder.instance;
      }
      }
      
    5. 枚举
      public enum SingletonInstance5 {
      
      // 定义一个枚举元素,则这个元素就代表了SingletonInstance5的实例
      INSTANCE;
      
      public void singletonOperation(){
          // 功能处理
      }
      }
      
      测试代码
      public static void main(String[] args) {
        SingletonInstance5 s1  = SingletonInstance5.INSTANCE;
        SingletonInstance5 s2  = SingletonInstance5.INSTANCE;
        System.out.println(s1 == s2); // 输出的是 true
        }
      

    单例模式应用场景

    1. Windows中的任务管理器就是典型的单例模式
    2. 操作系统的文件系统,也是大的单例模式实现的具体例子,一个操作系统只能有一个文件系统。
    3. 数据库连接池的设计一般也是采用单例模式,因为数据库连接是一种数据库资源。数据库软件系统中使用数据库连接池,主要是节省打开或者关闭数据库连接所引起的效率损耗,这种效率上的损耗还是非常昂贵的,因为何用单例模式来维护,就可以大大降低这种损耗。
    4. jdk中的Runtime.getRuntime();方法就是单例模式
      Runtime r = Runtime.getRuntime();
      Runtime r1 = Runtime.getRuntime();
          if (r1 == r) {
              System.out.println("他们是相同的");
          }
      try {
              r.exec("notepad"); // 打卡一个记事本程序。你可以再cmd敲个notepad试试
          } catch (Exception e) {
              System.out.println("Error executing notepad.");
          }
      

    相关文章

      网友评论

          本文标题:单例模式

          本文链接:https://www.haomeiwen.com/subject/washoqtx.html