拥有如此复杂的C++类设计的目的是什么?

aik*_*khs 11 c++ design-patterns

我遇到了一个开源的C++代码,我很好奇,为什么人们这样设计类?

首先,首先是Abstract类:

class BaseMapServer
    {
    public:
        virtual ~BaseMapServer(){}

        virtual void LoadMapInfoFromFile(const std::string &file_name) = 0;
        virtual void LoadMapFromFile(const std::string &map_name) = 0;
        virtual void PublishMap() = 0;
        virtual void SetMap() = 0;
        virtual void ConnectROS() = 0;
    };
Run Code Online (Sandbox Code Playgroud)

这里没什么特别的,有一个抽象类可以有几个很好理解的原因.所以从这一点来看,我想也许作者希望在其他课程中分享共同的特征.所以这是下一个类,它是一个单独的类,但实际上包含上面提到的类型抽象类的指针(实际的cpp文件,其他两个类是头文件):

class MapFactory
{
    BaseMapServer *CreateMap(
            const std::string &map_type,
            rclcpp::Node::SharedPtr node, const std::string &file_name)
        {
            if (map_type == "occupancy") return new OccGridServer(node, file_name);
            else
            {
                RCLCPP_ERROR(node->get_logger(), "map_factory.cpp 15: Cannot load map %s of type %s", file_name.c_str(), map_type.c_str());
                throw std::runtime_error("Map type not supported")
            }
        }
};
Run Code Online (Sandbox Code Playgroud)

现在有趣的是,这里是抽象类的子类:

class OccGridServer : public BaseMapServer
    {
    public:
        explicit OccGridServer(rclcpp::Node::SharedPtr node) : node_(node) {}
        OccGridServer(rclcpp::Node::SharedPtr node, std::string file_name);
        OccGridServer(){}
        ~OccGridServer(){}

        virtual void LoadMapInfoFromFile(const std::string &file_name);
        virtual void LoadMapFromFile(const std::string &map_name);
        virtual void PublishMap();
        virtual void SetMap();
        virtual void ConnectROS();

    protected:
        enum MapMode { TRINARY, SCALE, RAW };

        // Info got from the YAML file
        double origin_[3];
        int negate_;
        double occ_th_;
        double free_th_;
        double res_;
        MapMode mode_ = TRINARY;
        std::string frame_id_ = "map";
        std::string map_name_;

        // In order to do ROS2 stuff like creating a service we need a node:
        rclcpp::Node::SharedPtr node_;

        // A service to provide the occupancy grid map and the message with response:
        rclcpp::Service<nav_msgs::srv::GetMap>::SharedPtr occ_service_;
        nav_msgs::msg::OccupancyGrid map_msg_;

        // Publish map periodically for the ROS1 via bridge:
        rclcpp::TimerBase::SharedPtr timer_;
    };
Run Code Online (Sandbox Code Playgroud)

MapFactory班级的目的是什么?

更具体一点 - 创建一个包含Abstract类的指针的类的优点是什么?BaseMapServer它是一个构造函数(我相信),这个奇怪的构造函数为被调用的新对象创建一个内存OccGridServer并返回它?我只是写这个而感到困惑.我真的想成为一个更好的C++编码器,我迫切希望了解这些代码设计背后的秘密.

dbu*_*ush 5

MapFactory类用于创建正确的子类的实例BaseMapServer基于传递给它的参数.

在这种特殊情况下,只有一个子类实例,但也许有计划添加更多.然后,当添加更多时,工厂方法可能如下所示:

BaseMapServer *CreateMap(
        const std::string &map_type,
        rclcpp::Node::SharedPtr node, const std::string &file_name)
    {
        if (map_type == "occupancy") return new OccGridServer(node, file_name);
        // create Type2Server
        else if (map_type == "type2") return new Type2Server(node, file_name);   
        // create Type3Server
        else if (map_type == "type3") return new Type3Server(node, file_name);
        else
        {
            RCLCPP_ERROR(node->get_logger(), 
                         "map_factory.cpp 15: Cannot load map %s of type %s", 
                         file_name.c_str(), map_type.c_str());
            throw std::runtime_error("Map type not supported")
        }
    }
Run Code Online (Sandbox Code Playgroud)

这样做的好处是,调用者不需要知道正在使用的确切子类,实际上,底层子类可能会更改甚至被替换,而不需要修改调用代码.工厂方法为您内化了这个逻辑.