JavaScript设计模式面试真题(一)

JavaScript设计模式面试真题(一)

题目

quesiton

  • 画出UML类图
  • 用ES6语法写出该示例

解答

answer

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
class Car{
constructor(number,name){
this.number=number
this.name=name
}
}

class kuaizhe extends Car{
constructor(number,name){
super(number,name)
this.price=1 }
}

class zhuanche extends Car{
constructor(number,name){
super(number,name)
this.price=2
}
}

class Trip{
constructor(car){
this.car=car
}

start(){
console.log(`开始,名称:${this.car.name},车牌号:${this.car.number}`)
}

end(){
console.log(`借宿,金额:${this.car.price*5`)
}
}

let car =new kuaiche(100,'kuai')
let trip=new Trip(car)
trip.start()
trip.end()

问题

ques

解答

UML
ans

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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
class Car{
constructor(num){
this.num=num
}
}

// 摄像头
class Camera{
// constructor
shot(car){
retrun {
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)

const i =parseInt(Math.random()*100%100)
const place=this.floors[0].place[i]
place.in()
info.place=place

this.carList[car.num]=info
}
out(car){
cosnt info=this.carList[car.num]
cosnt 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.emptyPlace}`
}).join('\n')
}
}
// 层
class Floor{
constructor(index,places){
this.index=index
this.palces=places||[]
}

emptyPlaceNum(){
let num=0
this.places.forEach(p=>{
if(!p.empty){
num+=1
}
})
return num

}
}

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

//test------------------
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)

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

console.log('car1 in')
console.log(park.emptyNum())
park.in(car1)

park.out(car1)