学习了ts,不能没有一个综合实例,这不,本身作了一个,分享下。
实例是设计一辆汽车,它有一个抽象类,抽象类再实现一个接口,先定义好枚举学习
//档位 enum Gear { First=1, Second=3, Third=5 } //汽车颜色 enum Color { White, Red }
再定义接口,定义汽车启动,驾驶及最后的距离 以下:this
interface Drivable { //启动 start(): void; //驾驶 drive(time: number, speed: Gear): boolean; //具体位置 getPosition(): number }
接着设计抽象类,实现接口通用部分,设计
abstract class Car implements Drivable { protected _isRunning: boolean; protected _distanceFromStart: number; constructor() { this._isRunning = false; this._distanceFromStart = 0; } public start() { this._isRunning = true; } abstract drive(time: number, speed: Gear): boolean; public getPosition(): number { return this._distanceFromStart; } }
接着是咱们的具体实现类了,以下:code
//派生类 class Civic<T extends Color> extends Car { private color: Color; constructor(T) { super(); this.color = T; } public drive(time: number, speed: Gear): boolean { if (this._isRunning) { this._distanceFromStart += time*speed; return true; } return false; } public getColor(): string { return Color[this.color] } }
而后执行,以下:接口
let civic = new Civic(Color.Red); civic.start(); civic.drive(10, Gear.First); civic.drive(60, Gear.Third); document.body.innerHTML = "distance:"+civic.getPosition()+',color:'+civic.getColor()
运行程序,能够看到汽车运行的距离。
如有疑问,请加群:654979292ci