gpt4 book ai didi

C++ 全局访问类属性时应该使用哪种设计模式

转载 作者:行者123 更新时间:2023-11-28 01:37:19 24 4
gpt4 key购买 nike

问题很简单。目前我正在做一个项目,它有一个类,我们称之为 ResourceHandler.cpp 。这个类有一些属性,其余类需要的方法。一些属性,如我可以获得的用户名、用户 ID,只需调用 resourceHandler->getUserName() 即可设置,反之亦然。我可以想到两种方法

方法1:使类成为单例并访问get、set方法。

方法 2 将类和属性设为静态并在不访问它们的情况下访问它们任何实例。

但我不确定它们中的任何一个是否属于正确的设计。解决此类问题的理想方法应该是什么?

最佳答案

好吧,如果你想要一些高性能的东西。使用这两种方法中的任何一种。

但是如果你想要像其他语言一样良好的编码实践。你可以尝试这样的事情:

class User {
private:
int id;
string name;
public:
User(int id, const string &name): id(id), name(name) {}
inline int getId() const { return id; }
inline const string &getName() const { return name; }

// Make a shared object of the User class
static shared_ptr<User> currentUser;

static inline void logIn(int id, const string &name) {
User::currentUser = std::make_shared<User>(id, name);
}
};

shared_ptr<User> User::currentUser = 0;

void doSomethingLengthyWithUser(shared_ptr<User> user) {
static mutex mut; // The lock, for printing

// Simulate long running process
std::this_thread::sleep_for(std::chrono::milliseconds(3000));

// This (lock block) is only to make the printed output consistent
// Try to remove the block, and use the "cout" line only, and see.
{
lock_guard<mutex> l(mut);
cout << "Done it with: " << user->getName() << endl;
}
}

int main() {

// Login first user
User::logIn(1, "first");
cout << "Logged in: " << User::currentUser->getName() << endl;

// Now, we want to do something lengthy with the current user.
// If you were in a different class, you could use the static variable
std::thread doWithFirst(doSomethingLengthyWithUser, User::currentUser);

// Login the second user
User::logIn(2, "second");
cout << "Logged in: " << User::currentUser->getName() << endl;

// Do the lengthy operation with the second also
std::thread doWithSecond(doSomethingLengthyWithUser, User::currentUser);


// Wait for the second thread to end;
doWithSecond.join();

return 0;
}

为什么会这样?

如果有一个冗长的用户相关操作,你突然改变了当前用户。作为一个 shared_ptr 这使得它在操作内部仍然未发布和未更改,而静态变量将引用新变量。另一种方法是使用复制,但在 C++ 中它可能会导致一些性能问题。

关于C++ 全局访问类属性时应该使用哪种设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48728482/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com