在创建一个数据库实例的时候,我们不需要每个请求都创建一个实例,所以在设计类的时候,使用单例模式,同时使用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')