zl程序教程

您现在的位置是:首页 >  后端

当前栏目

js--面向对象分析实例

2023-09-27 14:26:50 时间

学习资源推荐


  • 微信扫码关注公众号 :前端前端大前端,追求更精致的阅读体验 ,一起来学习啊
  • 关注后发送关键资料,免费获取一整套前端系统学习资料和老男孩python系列课程
    在这里插入图片描述

学习资源推荐

需求

某停车场,分3层,每层100车位
每个车位都能监控到车辆的驶入和离开
车辆进入前,显示每层的空余车位数量
车辆进入时,摄像头可识别车牌号和时间
车辆出来时,出口显示器显示车牌号和停车时长

代码

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


class Camera {
    shot(car) {
        return {
            num: car.num,
            inTime: Date.now()
        }
    }
}

class Screen {
    show(car, inTime) {
        console.log('车牌号:', car.num);
        console.log('停车时间:', Date.now() - inTime);
    }
}
class Park {
    constructor(floors = []) {
        this.floors = floors;
        this.Camera = new Camera();
        this.Screen = new Screen();
        this.carList = []
    }


    in(car) {

        const info = this.Camera.shot(car);


        let i = parseInt(Math.random()) * 100
        let place = this.floors[0].places[i];

        place.in();
        info.place=place
        this.carList[car.num] = info;



    }
    out(car) {

        const info = this.carList[car.num];
        let place=info.place;
        place.out();
        this.Screen.show(car, info.inTime)

        delete this.carList[car.num]

    }

    emptyNum() {
        return this.floors.map(item => {
            return `${item.index}层还有${item.emptyPlaceNum()}停车位`
        }).join('\n')
    }
}

class Floor {
    constructor(index, places = []) {
        this.index = index;//第几层
        this.places = places;//停车位
    }
    emptyPlaceNum() {
        let index = 0;
        this.places.forEach(item => {
            if (item.isEmpty) {
                index++
            }
        })

        return index

    }
}

class Place {
    constructor() {
        this.isEmpty = true;
    }
    in() {
        this.isEmpty = false
    }
    out() {
        this.isEmpty = true
    }
}





let floors = [];

for (let i = 0; i < 3; i++) {
    let places = [];
    for (let j = 0; j < 100; j++) {
        places[j] = new Place()
    }
    floors[i] = new Floor(i + 1, places)

}


let park = new Park(floors);

let car1 = new Car(100)
let car2 = new Car(200)
let car3 = new Car(300)

console.log("第一辆车进入")
console.log(park.emptyNum())
park.in(car1);
console.log("第二辆车进入")
console.log(park.emptyNum())
park.in(car2);

console.log("第三辆车进入")
console.log(park.emptyNum())
park.in(car3);

console.log("第一辆车离开")
park.out(car1);
console.log("第二辆车离开")
park.out(car2);

console.log("第三辆车进入")
console.log(park.emptyNum())
park.in(car3);
console.log("第三辆车离开")
park.out(car3);
console.log(park.emptyNum())