『設計電梯類』,每個人對於電梯都有一個具體的認知,但面試者自己的理解是否就和面試官一致呢?避免想當然的去假設,多問問題,明確細節,比如:
-
電梯的容量(載重,載入數)是否考慮?
-
電梯的運行范圍是幾層到幾層?
-
是一部電梯還是多個電梯?
當我們相對了解題目的具體需求之后,設計電梯類時要從OO設計基本原則入手,比如封裝性,本質上就是講class內部的狀態封裝在內,對外提供合理的方法接口。
從方法的角度思考相對直觀:根據題目的需求,一個基本的電梯類應該提供什么樣的方法呢?
-
開門、關門
-
移動到下一目標樓層
-
接受去目標樓層的請求
以上都是最直觀、最基本的方法,相對應的就是電梯內部的基本狀態:
-
電梯門的開關狀態 (開關門會影響該狀態)
-
運行方向(移動會影響該狀態,該狀態也影響下一步行動);
-
當前樓層 (移動會影響該狀態,該狀態也影響下一步行動)
-
需要停的樓層集合(接受去某樓層的請求會影響該狀態,該狀態影響下一步行動);
-
--You can't design everything during the system. You need to show all operation and implement one. For example /* ------------------------ Elevator System ------------------------ Use Cases : 1. Passanger/User wants to go to the different floor. 2. He request the floor number in the elevator system 3. Elevator picks the person 4. Elevator delivers the person to the floor. ----------------- What if elevator is running ? -> If it is going to the same direction, it will pick the person on its way -> If it is open state, it will wait to get it running state -> If elevator is in halt/maintainance state, it will not respond -> If it is waiting state, it will start moving. ------------------ Alternate usecases---- -> Elevator has a maximum number of floor. -> A user can request for call, alarm, stop, keep door open/close such commands -> Elevator has preferrences like door will keep open for 5 seconds for loading or unloading. ------------------ Let's find out the classes, attribute and datastructure by doing language analysis --------------------------------------------------------------------------------- 1. Passanger -> srcFloor -> destinationFloor *issueRequest(int dest) *issueAlarm() *issueStop() 2. Elevator -> state -> direction -> speed -> targetted Floors *openDoor() *moveUp() *moveDown() *stop() *startAlarm() 3. State (Enum) -> Running, Open, Idle, Stopped, Alarmed 4. Floor -> number -> isServiced -------------------------------------------------------------------------------------- Command Pattern ( How Elevator will listen to request ) -------------------------------------------------------------------------------------- /* / class Elevator{ State currState; int directon; int speed; Floor[] targettedFloors; void openDoor() { //Implementation of open door } void closeDoor() { //Implementation of closing door } } interface Request { boolean execute(Elevator e); } class DoorOpenRequest implements Request{ public boolean execute(Elevator e) { e.openDoor(); } } class CloseDoorRequest implements Request{ public boolean execute(Elevator e) { e.closecloseDoor(); } } --- If passanger wants to issue request Command odCommand = new OpenDoorCommand(Elevator.getInstance()); odCommand.execute();
