面向对象的酒店预订系统设计

Object oriented design for hotel reservation system

本文关键字:系统设计 酒店预订 面向对象的      更新时间:2023-10-16

我正在为即将到来的面试练习面向对象设计。我的问题是关于酒店预订系统的设计:-系统应该能够返回特定类型的开放房间或返回酒店中的所有开放房间。-酒店的房间有普通房、豪华房、名流房等多种类型。

到目前为止,我已经提出了以下类:

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()方法的实现感到困惑,我正在检查类型(我认为应该通过多态性以某种方式处理)。有没有更好的方法来设计这个系统,使搜索和allOpenRooms方法可以在不显式检查对象类型的情况下实现?

遍历子类对象询问它们是什么类型并不能很好地说明o-o设计。你真的需要在不知道每个房间是什么类型的情况下对所有房间做一些你想做的事情。例如,打印出房间的每日房间菜单(不同类型的房间可能不同)。故意寻找子类对象的类型,虽然没有错,但不是很好的o-o风格。如果你只是想这样做,就像其他受访者说的那样,只要有一组属性的"房间"。

你总是可以让一个房间携带它的真实类型,而不是比较对象类型:

enum RoomType
{
  RegularRoom,
  luxuryRoom
};
class Room{
public:
  explicit Room(RoomType room_type) : room_type_(room_type) { }
  virtual ~Room(){}
  RoomType getRoomType() const { return room_type_; }
private:
  RoomType room_type_;     // carries room type
};
class regularRoom: public Room{
public:
  regularRoom() : Room(RegularRoom){ }
};

Room search(Room *aRoom)
{
   //Search room of a specific type
   for(size_t i=0;i<openRooms.size();i++)
   {
     if (aRoom->getRoomType() == RegularRoom)  // <<-- compare room type
     {
         // do something
      }
    }
};

不同类型的房间有不同的行为吗?从你给出的描述,这是不是继承的情况应该使用。每个房间都有一个属性,类型最简单的形式就是枚举。

最简单的方法是使用@billz建议的Room类型枚举。这种方法的问题是,您必须不要忘记向枚举添加一个值,并在每次向系统添加新类型的Room时使用它。必须确保枚举值只使用一次,每个类只使用一次。

但是,另一方面,基于继承的设计只有在层次结构的类型共享共同行为时才有意义。换句话说,无论其类型如何,您都希望以相同的方式使用它们。 IMPO, OO/继承设计并不是更好的方法。

我做这类事情的怪异和可扩展的方式是通过打字员

通常,系统中的每种类型都有不同的搜索条件。而且,在许多情况下,对于不同类型的系统,此搜索的结果是不相同的(搜索豪华房间和搜索普通房间是不一样的,您可以使用不同的搜索条件和/或需要不同的搜索结果数据)。

为此,系统有三个类型列表:一个包含数据类型,一个包含搜索条件类型,一个包含搜索结果类型:
using system_data_types     = type_list<NormalRoom,LuxuryRoom>;
using search_criteria_types = type_list<NormalRoomsCriteria,LuxuryRoommsCriteria>;
using search_results_types  = type_list<NormalRoomSearchResults,LuxuryRoomSearchResults>;

请注意,type_lists以相同的方式排序。这很重要,如下所示。

所以搜索引擎的实现是:

class SearchEngine
{
private:
    std::vector<VectorWrapper*> _data_lists; //A vector containing each system data type in its own vector. (One vector for NormalRoom, one for LuxuryRoom, etc)
    //This function returns the vector that stores the system data type passed.
    template<typename T>
    std::vector<T>& _get_vector() {...} //Implementation explained below.
public:
     SearchEngine() {...}//Explanation below.
    ~SearchEngine() {...}//Explanation below.
    //This function adds an instance of a system data type to the "database".
    template<typename T>
    void addData(const T& data) { _get_vector<T>().push_back( data ); }
    //The magic starts here:
    template<typename SEARCH_CRITERIA_TYPE>//This template parameter is deduced by the compiler through the function parameter, so you can ommit it.
    typename search_results_types::type_at<search_criteria_types::index_of<SEARCH_CRITERIA_TYPE>> //Return value (The search result that corresponds to the passed criteria. THIS IS THE REASON BECAUSE THE TYPELISTS MUST BE SORTED IN THE SAME ORDER.
    search( const SEARCH_CRITERIA_TYPE& criteria)
    {
        using system_data_type = system_data_types::type_at<search_criteria_types::index_of<SEARCH_CRITERIA_TYPE>>; //The type of the data to be searched.
        std::vector<system_data_type>& data = _get_vector<system_data_type>(); //A reference to the vector where that type of data is stored.
        //blah, blah, blah (Search along the vector using the criteria parameter....)
    }
};

搜索引擎的使用方法如下:

int main()
{
    SearchEngine engine;
    engine.addData(LuxuryRoom());
    engine.addData(NormalRoom());
    auto luxury_search_results = engine.search(LuxuryRoomCriteria()); //Search LuxuryRooms with the specific criteria and returns a LuxuryRoomSearchResults instance with the results of the search.
    auto normal_search_results = engine.search(NormalRoomCriteria()); //Search NormalRooms with the specific criteria and returns a NormalRoomSearchResults instance with the results of the search.
}

引擎基于存储每个系统数据类型的一个向量。热机用一个向量来存储这些向量。我们不能有指向不同类型向量的多态引用/指针,所以我们使用std::vector:

的包装器。
struct VectorWrapper
{
    virtual ~VectorWrapper() = 0;
};
template<typename T>
struct GenericVectorWrapper : public VectorWrapper
{
    std::vector<T> vector;
    ~GenericVectorWrapper() {};
};
//This template class "builds" the search engine set (vector) of system data types vectors:
template<int type_index>
struct VectorBuilder
{
    static void append_data_type_vector(std::vector<VectorWrapper*>& data)
    {
        data.push_back( new GenericVectorWrapper< system_data_types::type_at<type_index> >() ); //Pushes back a vector that stores the indexth type of system data.
        VectorBuilder<type_index+1>::append_data_type_vector(data); //Recursive call
    }
};
//Base case (End of the list of system data types)
template<>
struct VectorBuilder<system_data_types::size>
{
    static void append_data_type_vector(std::vector<VectorWrapper*>& data) {}
};

因此SearchEngine::_get_vector<T>的实现如下:

template<typename T>
std::vector<T>& get_vector()
{
    GenericVectorWrapper<T>* data; //Pointer to the corresponing vector
    data = dynamic_cast<GenericVectorWrapper<T>*>(_data_lists[system_data_types::index_of<T>]); //We try a cast from pointer of wrapper-base-class to the expected type of vector wrapper
    if( data )//If cast success, return a reference to the std::vector<T>
        return data->vector;
    else
        throw; //Cast only fails if T is not a system data type. Note that if T is not a system data type, the cast result in a buffer overflow (index_of<T> returns -1)
}

SearchEngine的构造函数只使用VectorBuilder来构建向量列表:

SearchEngine()
{
    VectorBuilder<0>::append_data_type_vector(_data_list);
}

,析构函数只遍历删除vector的链表:

~SearchEngine()
{
    for(unsigned int i = 0 ; i < system_data_types::size ; ++i)
        delete _data_list[i];
}

这种设计的优点是:

  • 搜索引擎使用完全相同的接口用于不同的搜索(以不同系统数据类型为目标的搜索)。将数据类型"链接"到相应的搜索条件和结果的过程是在编译时完成的。

  • 该接口是类型安全的:对SearchEngine::search()的调用仅基于通过的搜索条件返回类型的结果。赋值结果错误在编译时被检测。例如:NormalRoomResults = engine.search(LuxuryRoomCriteria())生成编译错误( engine.search<LuxuryRoomCriteria>返回LuxuryRoomResults )

  • 搜索引擎是完全可扩展的:要向系统添加新的数据类型,您只需要将类型添加到类型列表中。搜索引擎的实现不改变

Room class

class Room{
    public:
        enum Type {
            Regular,
            Luxury,
            Celebrity
        };
        Room(Type rt):roomType(rt), isOpen(true) { }
        Type getRoomType() { return roomType; }
        bool getRoomStatus() { return isOpen; }
        void setRoomStatus(bool isOpen) { this->isOpen = isOpen; }
    private:
        Type roomType;
        bool isOpen;
    };

酒店类

class Hotel{
    std::map<Room::Type, std::vector<Room*>> openRooms;
    //std::map<Room::Type, std::vector<Room*>> reservedRooms;
public:
    void addRooms(Room &room) { openRooms[room.getRoomType()].push_back(&room); }
    auto getOpenRooms() {
        std::vector<Room*> allOpenRooms;
        for(auto rt : openRooms)
            for(auto  r : rt.second)
                    allOpenRooms.push_back(r);
        return allOpenRooms;
    }
    auto getOpenRoomsOfType(Room::Type rt) {
        std::vector<Room*> OpenRooms;
        for(auto r : openRooms[rt])
            OpenRooms.push_back(r);
        return OpenRooms;
    }
    int totalOpenRooms() {
        int roomCount=0;
        for(auto rt : openRooms)
            roomCount += rt.second.size();
        return roomCount;
    }
};

客户UseCase:

Hotel Marigold;
Room RegularRoom1(Room::Regular);
Room RegularRoom2(Room::Regular);
Room LuxuryRoom(Room::Luxury);
Marigold.addRooms(RegularRoom1);
Marigold.addRooms(RegularRoom2);
Marigold.addRooms(LuxuryRoom);
auto allRooms = Marigold.getOpenRooms();
auto LRooms = Marigold.getOpenRoomsOfType(Room::Luxury);
auto RRooms = Marigold.getOpenRoomsOfType(Room::Regular);
auto CRooms = Marigold.getOpenRoomsOfType(Room::Celebrity);
cout << " TotalOpenRooms : " << allRooms.size()
                            << "n Luxury : " << LRooms.size()
                            << "n Regular : " << RRooms.size()
                            << "n Celebrity : " << CRooms.size()
                            << endl;

TotalOpenRooms: 4
奢侈品:2
Regular: 2
名人:0

如果您真的想要检查一个房间是否与其他房间的类型相同,那么typeid()与其他方法一样好-并且它肯定比调用虚拟方法"更好"(至少从性能角度来看)。

另一种选择是根本没有单独的类,并将roomtype存储为成员变量(这当然是我设计它的方式,但这对于学习面向对象和继承不是一个很好的设计-当基类满足所有需求时,您无法继承)。