设计模式

39 阅读1分钟

设计模式

  • 为了解决 某一类问题的一个优化过的代码解决方案
  • 单例模式:
    • 一个构造函数,一生只能创建一个实例化对象
    • 准备一个变量默认值为null,然后在第一次实例化的时候 给这变量赋值为实例化对象
    • 后续在调用实例化的时候,就不再创建实例化对象了,而是拿到提前准备好的变量
    // function Person() {
    //   this.name = name
    //   console.log('实例化后会创建一个 弹出框')
    // }
    // new Person()
    class Dialog {
      constructor() {
        console.log('在页面中 创建了一个 弹出层')
      }
    }
    let instance = null
    function newDialog() {
      if(instance === null) {
        instance = new Dialog()
      }
      return instance
    }
    // 第一次调用,创建一个实例化对象然后给到instance中,并返回instance
    let d1 = newDialog()
    // 
    newDialog()
    newDialog()

单例模式升级1

    class Dialog {
      constructor() {
        console.log('在页面中 创建了一个 弹出层')
      }
    }
    /**
     * 升级1: 原本的instance变量为一个全局变量,本次利用自执行函数与闭包将其修改为了局部变量
     * */ 
    // let instance = null
    // function newDialog() {
    //   if(instance === null) {
    //     instance = new Dialog()
    //   }
    //   return instance
    // }
    const newDialog = (function() {
      // 自执行函数内 创建一个变量(局部变量)
      let instance = null
      return function() {
        if(instance === null) {
          instance = new Dialog()
        }
        return instance
      }
    })()
    // 第一次调用,创建一个实例化对象然后给到instance中,并返回instance
    let d1 = newDialog()
    let d2 = newDialog()

单例模式升级2

    const Dialog = (function() {
      let instance = null

      class Dialog {
        constructor(title) {
          this.title = title
          console.log('在页面中 创建了一个 弹出层')
        }
        setTitle(newTitle) {
          this.title = newTitle
        }
      }

      return function(type) {
        if(instance === null) {
          // 当前分支语句的代码 只会在第一次的时候执行
          instance = new Dialog()
        }
        // 此时的位置,每一次调用newDialog都会执行一次
        instance.setTitle(type)
        return instance
      }
    })()
    let d1 = Dialog('警告')
    console.log(d1)

    // 过了很久之后,第二次调用
    let d2 = Dialog('通用')
    console.log(d2)