功能:定义一个操作数据的库,支持 Mysql、Mssql、MongoDb
要求:Mysql、Mssql、MongoDb功能一样,都有add、update、delete、get方法
注意:约束统一的规范、以及代码重用
解决方案:需要约束规范所以要定义接口,需要代码重用所以用到泛型
1、接口:在面向对象的编程中,接口是一种规范的定义,它定义了行为和动作的规范
2、泛型:解决类、接口、方法的复用性
interface DBI<T> {
add(info: T): boolean;
update(info: T, id: number): boolean;
delete(id: number): boolean;
get(id: number): any[];
}
// 定义一个操作mysql数据库的类
// 要实现泛型接口,类也应该是泛型类
class MysqlDb<T> implements DBI<T> {
add(info: T): boolean {
console.log(info, 'MysqlDb');
return true
}
update(info: T, id: number): boolean {
throw new Error("Method not implemented.");
}
delete(id: number): boolean {
throw new Error("Method not implemented.");
}
get(id: number): any[] {
throw new Error("Method not implemented.");
}
}
// 定义一个操作mssql数据库的类
class MsSqlDb<T> implements DBI<T> {
constructor() {
console.log('数据库建立连接');
}
add(info: T): boolean {
console.log(info, 'MsSqlDb');
return true
throw new Error("Method not implemented.");
}
update(info: T, id: number): boolean {
throw new Error("Method not implemented.");
}
delete(id: number): boolean {
throw new Error("Method not implemented.");
}
get(id: number): any[] {
var list = [
{
title: '',
desc: ''
}
]
return list
throw new Error("Method not implemented.");
}
}
// 操作用户表 定义一个User类和数据库表做映射
class User {
username: string | undefined;
password: string | undefined
}
var u = new User()
u.username = '用户名'
u.password = '密码'
var oMy = new MysqlDb<User>(); // 类作为参数来约束数据传入的类型
oMy.add(u)
var oMs = new MsSqlDb<User>(); // 类作为参数来约束数据传入的类型
oMs.add(u)
var data = oMs.get(4)
console.log(data, '获取 id = 4 的数据');