sách gpt4 ai đã đi

c++ - 为所有类提供运行时参数的规范方法——全局?

In lại 作者:行者123 更新时间:2023-11-28 06:52:00 28 4
mua khóa gpt4 Nike

解决此类问题的规范 C++ 设计模式是什么?

我有一些共享多个类的多线程服务器。我需要为大多数类提供各种运行时参数(例如服务器名称、日志记录级别)。

在下面的伪 C++ 代码中,我使用了一个日志记录类的参数作为一个例子,但可能还有其他值需要在各种对象中访问。

特别是,Thread 对象需要有自己的日志类实例以避免损坏。

我可以将运行时参数设置为全局参数或静态参数,但它们似乎都有代码味道。同样,单例或将值传递给许多构造函数或初始值设定项似乎不是最优的或违反得墨忒耳法则。

Server 类(如下)中的 Thread 类目前我无法更改,尽管它可能会妨碍一些更优雅的事情。 :-/

请原谅下面的快速和肮脏的 C++ 代码;希望它能充分说明问题。

// p1.cpp
int main(int argc, char** argv) {
Log log(level, "p1");
Driver driver;
driver.exec(new p1Factory());
}
// p2.cpp
int main(int argc, char** argv) {
Log log(level, "p2");
Driver driver;
driver.exec(new p2Factory());
}
// p3 ... p7.cpp same as above

class Driver {
công cộng:
Driver() {}
void exec(GenericFactory * f) { factory = f; server.createThreads(); }
protected:
GenericFactory * factory;
Server server(GenericFactory * f);
};

class Server : public GenericServer {
protected:
class Thread : public IPCThread
{
friend class Server;
riêng tư:
Channel * channel;
Log threadLog;
công cộng:
Thread(Channel * c);
};

GenericFactory * factory;

công cộng:
Server(GenericFactory * f);
void createThreads();
};

Server::createThreads() {
for (int i = 0; i < threads; ++i) {
thread[i] = new Server::Thread(factory->getChannel());
// I need to set the threadLog's level and ident string to the
// same values they had in the top-level global log. How?
}
}

1 Câu trả lời

我不知道đặc điểm kỹ thuật 方法,但这里有一些技巧。

存储为全局变量
将值复制到全局变量中。将头文件中的变量名称提供为 bên ngoài.

将参数传递给需要变量的每个函数
一些反对单例的人说要将变量传递给所有需要它们的函数。

存储在配置函数/类中
您可以创建一个 Configuration 单例来读取和解析命令行。该实体将具有读取参数但不写入参数的方法。

抱歉,我没有看到“一刀切”的方法。选择一个并使用它。如果您无法决定,请掷骰子或掷硬币。

关于c++ - 为所有类提供运行时参数的规范方法——全局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23791478/

28 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com