我正在为即将到来的面试练习面向对象设计。我的问题是关于酒店预订系统的设计: - 系统应该能够返回特定类型的开放房间或返回酒店中的所有开放房间。 - 酒店房型分为普通房、豪华房、名人房等多种房型。
到目前为止,我提出了以下类:
Class Room{
//Information about room
virtual string getSpecifications(Room *room){};
}
Class regularRoom: public Room{
//get specifications for regular room
}
Class luxuryRoom: public Room{
//get specifications for regular room
}
//Similarly create as many specialized rooms as you want
Class hotel{
vector<Room *>openRooms; //These are all the open rooms (type casted to Room type pointer)
Public:
Room search(Room *aRoom){ //Search room of a specific type
for(int i=0;i<openRooms.size();i++){
if(typeid(*aRoom)==typeid(*openRooms[i])) return *openRooms[i];
}
}
vector<Room> allOpenRooms(){//Return all open rooms
...
}
}
我对检查类型的 hotel.search() 方法的实现感到困惑(我认为应该以某种方式通过多态处理)。有没有更好的方法来设计这个系统,以便可以在不显式检查对象类型的情况下实现 search 和 allOpenRooms 方法?
最佳答案
遍历子类对象并询问它们是什么类型并不是 o-o 设计的一个很好的例证。您真的需要对所有房间都做一些您想要做的事情,而不知道每个房间是什么类型。例如,打印出房间的每日房间菜单(不同类型可能有所不同)。 故意寻找子类对象的类型,虽然没有错,但不是很好的 o-o 风格。如果您只是想这样做,正如其他受访者所说,只需拥有具有一组属性的“房间”。
关于c++ - 酒店预订系统的面向对象设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17131407/