1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| class Car { constructor(make, model, year) { this.make = make this.model = model this.year = year } printDetail() {} }
class SportCar extends Car { constructor(make, model, year) { super(make, model, year) this.carType = 'Sport' }
printDetail() { console.log(`Make: ${this.make}, Model: ${this.model}, Year: ${this.year}, Car Type: ${this.carType}`); } }
class TruckCar extends Car { constructor(make, model, year) { super(make, model, year) this.carType = 'Truck' }
printDetail() { console.log(`Make: ${this.make}, Model: ${this.model}, Year: ${this.year}, Car Type: ${this.carType}`); } }
class CarFactory { constructor(make, model, year, carType) { this.car = null; this.make = make this.model = model this.year = year
switch (carType) { case 'Sport': this.car = new SportCar(make, model, year) break; case 'Truck': this.car = new TruckCar(make, model, year) break; default: throw new Error('没有这个车型!') } }
printDetail() { this.car.printDetail() } }
const sportCar = new CarFactory("Mercedes", "AMG GT", 2022, "Sport"); sportCar.printDetail()
const truckCar = new CarFactory("Volvo", "VNL860", 2021, "Truck"); truckCar.printDetail()
|