停车场简易设计模式

本文介绍了如何设计一个简单的停车场系统,包括汽车、摄像头、显示屏、停车场、楼层和停车位等类的定义。系统能记录车辆进入和离开,显示各层空余车位数,以及在车辆离开时显示停车时长。通过实例展示了车辆的进出操作以及空车位数量的查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:

1.某停车场, 分三层, 每层100 车位

2.每个车位都能监控到车辆的进入和离开

3.车辆进入前,显示每层的空余车位数量

4.车辆进入时,摄像头可识别车牌号和进入时间

5.车辆出来时,出口显示屏显示车牌号和停车时长

 

//汽车

class Car {
    constructor(carId){
        this.carId = carId
    }
}


//摄像头
class Camera {
    shot(car){
        return {
            name: car.carId ,
            inTime: Date.now()
        }
    }
}

//显示屏

class Screen {
    show(car, inTime) {
        console.log('车牌号: ', car.carId)
        console.log('停车时间: ', Date.now() - inTime)
    }
}

//停车场
class ParkingLot {
    constructor(floors) {
        this.floors = floors || []    //记录每层停车位数量
        this.camera = new Camera()    //记录车辆信息,停车时间
        this.screen = new Screen() //显示车辆停车信息
        this.carList = {} //存储摄像头拍摄返回的车辆信息
    }

    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.carId] = info
        
    }

    out(car) {
        //获取信息
        const info = this.carList[car.carId]

        //将停车位清空
        const place = info.place
        place.out()

        //显示时间
        this.screen.show(car, info.inTime)

        //清空记录
        delete this.carList[car.carId]
    }

    //返回停车场所有空余车位数量
    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(empty){
        this.empty = true
    }

    in(){
        this.empty = false
    }

    out(){
        this.empty = true
    }
}


//测试

//初始化停车场
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 parkingLot = new ParkingLot(floors)

//初始化车辆
const car1 = new Car(100)
const car2 = new Car(200)
const car3 = new Car(300)


console.log('第一辆车进入')
console.log(parkingLot.emptyNum())
parkingLot.in(car1)
console.log('第二辆车进入')
console.log(parkingLot.emptyNum())
parkingLot.in(car2)
console.log('第一辆车离开')
parkingLot.out(car1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值