/**
* 某停车厂,分3层,每层100车位
* 每个车位都能监控到车辆的是驶入和离开
* 车辆进入前,显示每层的空余车位数量
* 车辆进入时,摄像头可识别车牌号和时间
* 车辆出来时,出口显示器显示车牌和停车时间
*/
// 画出UML类图
//车辆类class Car { constructor(num) { this.num = num; }}//摄像头类class Camera { constructor() {} shot(car) { return { num: car.num, inTime: Date.now() }; }}//显示屏类class Screen { constructor() {} show(car, inTime) { console.log('车牌号:', car.num); console.log('停车时间:', Date.now() - inTime); }}//停车场类class Park { constructor(floors) { this.floors = floors || []; this.carList = {}; //存储摄像头拍摄返回的车辆信息 this.camera = new Camera(); //摄像头 this.screen = new Screen(); } in(car) { // 通过摄像头获取车辆进入信息 const info = this.camera.shot(car); // 停到某个车位,这里取随机数 const i = parseInt((Math.random() * 100) % 100); // 先假设位于一层的该车位 const place = this.floors[0].places[i]; place.in(); info.place = place; //记录信息 this.carList[car.num] = info; } out(car) { //获取信息 const info = this.carList[car.num]; //将车位清空 const place = info.place; place.out(); //显示时间 this.screen.show(car, info.inTime); //清空记录 delete this.carList[car.num]; } emptyNum() { return this.floors .map(floor => { return `${floor.index} 层还有 ${floor.emptyPlaceNum()}个空闲车位`; }) .join('\n'); }}// 层类class Floor { constructor(index, places) { this.index = index; this.places = places || []; } emptyPlaceNum() { let num = 0; this.places.forEach(p => { if (p.empty) num++; }); return num; }}//车位类class Place { constructor() { this.empty = true; } in() { this.empty = true; } out() { this.empty = false; }}复制代码
//测试代码//初始化停车场const floors = [];for (let i = 0; i < 3; i++) { const places = []; for (let j = 0; j < 100; j++) { places[j] = new Place(); } floors[i] = new Floor(i + 1, places);}const park = new Park(floors);var car1 = new Car(100);var car2 = new Car(200);var car3 = new Car(300);console.log('第一辆车进入');park.in(car1);console.log(park.emptyNum());console.log('第二辆车进入');park.in(car2);console.log(park.emptyNum());console.log('第一辆车离开');park.out(car1);console.log(park.emptyNum());console.log('第二辆车离开');park.out(car2);console.log(park.emptyNum());console.log('第三辆车进入');park.in(car3);console.log(park.emptyNum());console.log('第三辆车离开');park.out(car3);复制代码