- 某停車場,分3層,每層100車位
- 每個車位都能監控到車輛的駛入和離開
- 車輛進入前,顯示每層的空余車位數
- 車輛進入時,攝像頭可識別車牌號和時間
- 車輛出來時,出口顯示器顯示車牌號和停車時長
UML 類圖
邏輯代碼示例
1 // 車輛 2 class Car { 3 constructor(num) { 4 this.num = num // 車牌號 5 } 6 } 7 8 // 攝像頭 9 class Camera { 10 shot(car) { 11 return { 12 num: car.num, // 記入車牌號 13 inTime: Date.now() // 記入車輛進入的時間 14 } 15 } 16 } 17 18 // 出口顯示屏 19 class Screen { 20 show(car, inTime) { 21 console.log('車牌號', car.num) 22 console.log('停車時間', Date.now() - inTime) // 該車牌號待的時長 23 } 24 } 25 // 停車場 26 class Park { 27 constructor(floors) { 28 this.floors = floors || [] // 停車場樓層 29 this.camera = new Camera() // 攝像頭實例 30 this.screen = new Screen() // 顯示器實例 31 this.carList = {} // 存儲攝像頭拍攝返回的車輛信息 32 } 33 in(car) { 34 // 通過攝像頭獲取信息 35 const info = this.camera.shot(car) 36 // 停到某個車位 37 const i = parseInt(Math.random() * 100 % 100) 38 const place = this.floors[0].places[i] 39 place.in() 40 info.place = place 41 // 記錄信息 42 this.carList[car.num] = info 43 } 44 out(car) { 45 // 獲取信息 46 const info = this.carList[car.num] 47 // 將停車位清空 48 const place = info.place 49 place.out() 50 // 顯示時間 51 this.screen.show(car, info.inTime) 52 // 清空紀錄 53 delete this.carList[car.num] 54 } 55 emptyNum() { 56 return this.floors.map(floor => { 57 return `${floor.index} 層還有 ${floor.emptyPlaceNum()} 個空閑車位` 58 }).join('\n') 59 } 60 } 61 62 // 層 63 class Floor { 64 constructor(index, places) { 65 this.index = index // 第幾層 66 this.places = places || [] // 停車位 67 } 68 // 該層的停車位還有幾個停車位是空閑的 69 emptyPlaceNum() { 70 let num = 0 71 this.places.forEach(p => { 72 if (p.empty) { 73 num = num + 1 74 } 75 }); 76 return num 77 } 78 } 79 80 // 車位 81 class Place { 82 constructor() { 83 this.empty = true // 當前停車位是否是空閑狀態 84 } 85 in() { 86 this.empty = false 87 } 88 out() { 89 this.empty = true 90 } 91 } 92 93 94 // 測試----- 95 // 初始化停車場 96 const floors = [] // 假設有停車場為三層 97 for (let i = 0; i < 3; i++) { 98 const places = [] // 假設每層停車場共有100個停車位 99 for (let j = 0; j < 100; j++) { 100 places[j] = new Place() // 創建100個停車位 101 } 102 floors[i] = new Floor(i + 1, places) // 創建停車場的樓層 103 } 104 // console.log(floors) 105 const park = new Park(floors) 106 console.log(park) 107 // 初始化車輛 108 const car1 = new Car(100) 109 const car2 = new Car(200) 110 const car3 = new Car(300) 111 112 console.log('第一輛車進入') 113 console.log(park.emptyNum()) 114 park.in(car1) 115 console.log('第二輛車進入') 116 console.log(park.emptyNum()) 117 park.in(car2) 118 console.log('第一輛車出去') 119 park.out(car1)