问题有三个,在注释里,大佬们有时间帮忙看下吧,20行左右的代码,辛苦了~
// 父类
class Database {
private readonly config // 连接数据库的配置
readonly database // 数据库的实例
constructor(config: Config) {
this.config = config // 记录下 config
this.database = app.database() // 连接数据库,并拿到实例
}
// 返回指定集合的实例
public collection(name: string): Collection {
return new Collection(this.config, name)
}
}
// 子类
class Collection extends Database {
readonly _collection // 集合的实例
// 调用父类方法,创建集合实例
constructor(config: Config, name: string) {
super(config)
// 问题一:执行下面这句,为啥不会递归呢?
this._collection = this.database.collection(name)
}
// 添加 略
add() {
}
// 查找 略
find() {
}
}
// 问题二:在下面的使用中,是不是实例化了2个 database 对象
const database = new Database({ ... })
const user = database.collection('user')
user.find( ... )
// 问题三:有什么更好的写法吗
this.database.collection(name)
不会递归,注意this.database
是app.database()
而不是自定义的Database
类new Collection(this.config, name)
会实例化一个Collection
,其继承于Database
建议就是不要继承,因为
Database
和Collection
不是继承关系,继承会导致每次database.collection()
都会连接一次数据库,改成new Database
连接一次,new Collection
直接在已有连接上获取collection
即可