- 功能: 定义一个操作,支持mysql, mssql, mongodb
- 要求: mysql, mussel, mongodb功能一样,都有add, update, delete, get方法
- 注意: 约束统一的规范,代码重用
- 解决方案: 需要约束规范所以要定义接口,需要代码重用,所以需要用到泛型
- 接口:在面向对象的编程中,接口是一种规范的定义,它定义了行为和动作的规范
- 泛型:泛型就是解决类、接口、方法的复用性。
interface DB<T>{
add(info:T):boolean;
update(info:T,id:number):boolean;
delete(info:T,id:number):boolean;
get(info:T, id:number):any[];
}
class MySqlDB<T> implements DB<T>{
add(info: T): boolean {
return true;
}
update(info: T, id: number): boolean {
return true;
}
delete(info:T, id: number): boolean {
return true;
}
get(info: T, id: number): any[] {
let result = [
{username:"test1", password:"123456",id:1},
{username:"test2", password:"123456",id:2},
{username:"test3", password:"123456",id:3},
{username:"test4", password:"123456",id:4}
];
return result;
}
}
class MsSqlDB<T> implements DB<T>{
add(info: T): boolean {
throw new Error("Method not implemented.");
}
update(info: T, id: number): boolean {
return true;
throw new Error("Method not implemented.");
}
delete(info: T, id: number): boolean {
throw new Error("Method not implemented.");
}
get(info: T, id: number): any[] {
throw new Error("Method not implemented.");
}
}
class MongoDB<T> implements DB<T>{
add(info: T): boolean {
throw new Error("Method not implemented.");
}
update(info: T, id: number): boolean {
throw new Error("Method not implemented.");
}
delete(info: T, id: number): boolean {
throw new Error("Method not implemented.");
}
get(info: T, id: number): any[] {
throw new Error("Method not implemented.");
}
}
class User{
username:string | undefined;
password:string | undefined;
}
let user1 = new User();
user1.username = "zhangsan";
user1.password = "123456";
let mysqldb = new MySqlDB<User>();
mysqldb.add(user1);
mysqldb.update(user1,1);
console.log(mysqldb.get(user1,1));
console.log(mysqldb.delete(user1,1));