具有相同方法的静态和非静态版本是否不好设计

Chr*_*nov 0 c++ design-patterns

我面临的问题与记录器库有关。我可以创建自己的记录器,但是同时,我希望能够使用“默认”或“全局”记录器进行操作。

因此,我认为记录器类的某些方法应具有静态版本,这些静态版本将处理此“默认”记录器。最终在设计方面感觉不对。

这是我想做的一个例子

std::shared_ptr<lwlog::logger> core_logger = std::make_shared<lwlog::logger>("LOGGER");  //creating some custom logger
core_logger->critical("A very critical message!"); //logging from some custom logger

lwlog::logger::critical("A very critical message!"); //logging from default logger
Run Code Online (Sandbox Code Playgroud)

我的静态和非静态版本的方法的示例:

class LWLOG logger
{
public:
    explicit logger(const std::string& name);
    ~logger();

    void set_name(const std::string& loggerName);
    void set_logLevel_visibility(log_level logLevel);
    void set_pattern(const std::string& pattern);

    void info(const std::string& message);
    void warning(const std::string& message);
    void error(const std::string& message);
    void critical(const std::string& message);
    void debug(const std::string& message);

    static void info(const std::string& message);
    static void warning(const std::string& message);
    static void error(const std::string& message);
    static void critical(const std::string& message);
    static void debug(const std::string& message);
};
Run Code Online (Sandbox Code Playgroud)

Lig*_*ica 5

是的,那将非常令人困惑。

类中的成员函数执行任务。该任务由函数的名称以及(在某种程度上)是否为来描述static。具有两个名称相同但功能不同的成员函数static来完成两项不同的工作是完全无法使用的。

标准委员会也知道这一点,这就是为什么您提出的解决方案无法编译的原因

如果您的用户想使用其他类型的记录器,则可以随时使用其他实例。

您可以在名称空间中提供一个即时实例,因此用户可以执行以下操作:

lwlog::default_logger->critical("Using the default logger for this one");
Run Code Online (Sandbox Code Playgroud)