学习了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
26 声望1 粉丝