设计模式理解

工厂模式·抽象工厂—–抽象类约定的是功能,具体功能实现由后面继承的具体类来实现,游戏类代码会常见该设计模式
代码实现

  class baseSystem {
      createSystem () {
          // 定义整体的功能,具体类必须重写该方法
      }
  }
  class androidSystem extends baseSystem { // 具体实现的类
      createSystem () {
          // 用安卓的方式去操作系统
      }
  }
  class iosSystem extends baseSystem {
    createSystem () {
          // 用ios的方式去操作系统
    }
  }
复制代码

单例模式—保证一个类仅?️一个实例,并提供一个访问它的全局访问点(vuex的实现模式就是单例模式)
代码实现

  class Storage {
      constructor () {
         this.instance: ''
      }
      static getInstance () {
        if (!this.instance) {
          this.instance = new Storage()
        }
        return this.instance
      }
      setItem (key, val) {
        return localStorage.setItem(key, val)
      }
      getItem (key) {
        return localStorage.getItem(key)
      }
    }
    let s1 = Storage.getInstance()
    let s2 = Storage.getInstance()
    s1.setItem('name', '张三')
    s2.getItem('name') // 张三
    s1 === s2 // true
复制代码

原型模式
     对于原型链的理解
          es6中的class类本质上是原型链继承的一种语法糖,并不是新的对象继承模型

   class cat {
       constructor (name) {
           this.catName= name
       }
       meow () {
           console.log(this.catName + '喵喵喵')
       }
   }
   let cat = new Cat('小白')
   cat.meow() // 小白喵喵喵
复制代码

等价于es5的

  function Cat (name) {
      this.catName = name
  }
  Cat.prototype.meow = function () {
    console.log(this.catName + '喵喵喵')
  }
  let cat = new Cat('小白')
  cat.meow() // 小白喵喵喵
复制代码

prototype

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享