美文网首页
typeScript 单例模式

typeScript 单例模式

作者: col128 | 来源:发表于2018-11-08 17:51 被阅读0次

在创建一个数据库实例的时候,我们不需要每个请求都创建一个实例,所以在设计类的时候,使用单例模式,同时使用TypeScript的静态方法,和静态属性

interface DBOperations {
    query(str:string):boolean
    insert(str:string):boolean
    delete(str:string):boolean
    update(str:string):boolean
}

class MySQL implements DBOperations{
    private static instance:MySQL
    host:string
    port:number
    userName:string
    password:string
    dbName:string
    private constructor(host:string='127.0.0.1',port:number = 3306, userName:string='root',password:string,dbName:string='homeStread'){
        this.host = host
        this.port = port
        this.userName = userName
        this.password = password
        this.dbName = dbName
    }
    toString(){
        let _str =  `
        host:${this.host},
        port:${this.port},
        dbName:${this.dbName},
        userName:${this.userName},
        password:${this.password}
        `
        console.log(_str)
        return _str
    }
    static  getInstance() {
        if (!this.instance) {
            // @ts-ignore
            this.instance = new MySQL()
        }
        return this.instance
    }

    delete(str: string): boolean {
        console.log(`query:${str}`)
        return false;
    }

    insert(str: string): boolean {
        console.log(`delete:${str}`)
        return false;
    }

    query(str: string): boolean {
        console.log(`query:${str}`)
        return false;
    }

    update(str: string): boolean {
        console.log(`update:${str}`)
        return false;
    }
}

let mySQLInstance = MySQL.getInstance()
mySQLInstance.password = 'secret'
mySQLInstance.toString()
mySQLInstance.query('select * from table')

相关文章

  • typeScript 单例模式

    在创建一个数据库实例的时候,我们不需要每个请求都创建一个实例,所以在设计类的时候,使用单例模式,同时使用TypeS...

  • TypeScript单例模式

    单例模式 要点:一是某个类只能有一个实例;二是它必须自行创建这个实例;三是它必须自行向整个系统提供这个实例。 用处...

  • Typescript 单体/单例模式

    标签: 前端 设计模式 单体模式 单例模式 typescript 如果下面的代码你能轻易阅读,那么你已经熟悉单体模...

  • TypeScript 01——单例模式

    1、最简单单例写法 调用方式:GameMgr.instance.方法名(); 2、懒汉式写法 调用方式:GameM...

  • 【设计模式】单例模式

    单例模式 常用单例模式: 懒汉单例模式: 静态内部类单例模式: Android Application 中使用单例模式:

  • Android设计模式总结

    单例模式:饿汉单例模式://饿汉单例模式 懒汉单例模式: Double CheckLock(DCL)实现单例 Bu...

  • 2018-04-08php实战设计模式

    一、单例模式 单例模式是最经典的设计模式之一,到底什么是单例?单例模式适用场景是什么?单例模式如何设计?php中单...

  • 设计模式之单例模式详解

    设计模式之单例模式详解 单例模式写法大全,也许有你不知道的写法 导航 引言 什么是单例? 单例模式作用 单例模式的...

  • TypeScript中理解单例模式

    单例模式简单来说就是我们在应用中全程只会实例化一个对象,因为对于这种类型的类,没有必要实例化多次,只要用到一个就可...

  • Telegram开源项目之单例模式

    NotificationCenter的单例模式 NotificationCenter的单例模式分析 这种单例模式是...

网友评论

      本文标题:typeScript 单例模式

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