• Geek_aeb936
    2024-08-10 来自日本
    import { T1, T2, T3, Transportations } from './t2-1'; interface T<T extends Transportations> { type: T; run(): void; } interface Motorcycle extends T<Transportations.motorcycle> { make: number; } interface Car extends T<Transportations.car> { transmission: string; pow: number; id: 'T2'; } interface TruckType extends T<Transportations.truck> { capacity: number; } type Transporter = Motorcycle | Car | TruckType; let x1 = new T1(2021); let x2 = new T2('Automatic', 150, 'T2'); let x3 = new T3(1000); let transporters: Transporter[] = [x1, x2, x3]; function start() { transporters.forEach(x => { x.run(); }); } start();
    展开
    
    
  • Geek_aeb936
    2024-08-10 来自日本
    // t2-1.ts enum Transportations { motorcycle, car, truck } abstract class T { abstract type: Transportations; abstract run(): void; } class T1 extends T { type = Transportations.motorcycle as const; constructor(public make: number) { super(); } run() { console.log(`Running motorcycle with make ${this.make}`); } } class T2 extends T { type = Transportations.car as const; constructor( public transmission: string, public pow: number, public id = 'T2' as const ) { super(); } run() { console.log(`Running car with transmission ${this.transmission} and power ${this.pow}`); } } class T3 extends T { type = Transportations.truck as const; constructor(public capacity: number) { super(); } run() { console.log(`Running truck with capacity ${this.capacity}`); } } type Transporter = T; class MyController { run(x: Transporter) { x.run(); } } // CASE1:使用一个平台(单例)来为所有的transporter提供服务 class Platform { static transporters = new Array<Transporter>(); static controller = new MyController(); static runAll() { this.transporters.forEach((transporter) => { this.controller.run(transporter); }); } } // CASE2:平台将为每一个transporter配备一个独立的控制器 class Platform2 extends Array<[MyController, Transporter]> { runAll() { this.forEach(([controller, transporter]) => { controller.run(transporter); }); } } // let x1 = new T1(2021); // let x2 = new T2('Automatic', 150, 'T2'); // let x3 = new T3(1000); // Platform.transporters.push(x1, x2, x3); // Platform.runAll(); export { T1, T2, T3, Transportations };
    展开
    
    