运用TypeScript构建实例对象

进修了ts,不能没有一个综合实例,这不,本身做了一个,分享下。
实例是设想一辆汽车,它有一个抽象类,抽象类再完成一个接口,先定义好罗列

//档位
enum Gear {
    First=1, Second=3, Third=5
}
//汽车色彩
enum Color {
    White, Red
}

再定义接口,定义汽车启动,驾驶及末了的间隔 以下:

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;
    }
}

接着是我们的详细完成类了,以下:

//派生类
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()

运转顺序,能够看到汽车运转的间隔。
如有疑问,请加群:654979292

    原文作者:weistar103
    原文地址: https://segmentfault.com/a/1190000016233479
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞