美文网首页TypeScript程序员我爱编程
设计模式在 TypeScript 中的应用 - 单例模式

设计模式在 TypeScript 中的应用 - 单例模式

作者: 三毛丶 | 来源:发表于2017-12-23 10:40 被阅读543次

    定义

    只有一个实例,并提供全局访问。

    实现

    思路:用一个变量来标识当前是否已经为某个类创建过对象,如果是,则在下一次获取该类的实例时,直接返回之前创建的对象,否则返回新对象。

    饿汉模式

    特点:类加载时就初始化。

    class Singleton {
    
      private static instance = new Singleton()
    
      // 将 constructor 设为私有属性,防止 new 调用
      private constructor () {}
    
      static getInstance (): Singleton {
        return Singleton.instance
      }
    }
    
    const singleton1 = Singleton.getInstance()
    const singleton2 = Singleton.getInstance()
    console.log(singleton1 === singleton2) // true
    

    懒汉模式

    特点:需要时才创建对象实例。

    class Singleton {
      private static instance: Singleton
      
      private constructor () {}
    
      static getInstance (): Singleton {
        if (!Singleton.instance) {
          Singleton.instance = new Singleton()
        }
        return this.instance
      }
    }
    
    const singleton1 = Singleton.getInstance()
    const singleton2 = Singleton.getInstance()
    console.log(singleton1 === singleton2) // true
    

    简单栗子

    class Singleton {
      private constructor (name: string, age: number) {
        this.name = name
        this.age = age
      }
    
      private static instance: Singleton
    
      public name: string
      public age: number
    
      static getInstance (
          name: string,
          age: number
        ): Singleton {
        if (!this.instance) {
          this.instance = new Singleton(name, age)
        }
        return this.instance
      }
    }
    
    const singleton1 = Singleton.getInstance('Mary', 20)
    const singleton2 = Singleton.getInstance('Jack', 20)
    console.log(singleton1, singleton2)
    

    相关文章

      网友评论

        本文标题:设计模式在 TypeScript 中的应用 - 单例模式

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