防止单独调用成员函数

Preventing a member function from being called alone

本文关键字:成员 函数 调用 单独      更新时间:2023-10-16

在此代码中:

class Person {
    std::string name;
public:
    Person(const std::string& n) : name(n) {}
    void setName(const std::string& newName) {name = newName;}
};
class System {
    void changeName (Person* person, const std::string& newName) {
        person->setName(newName);  // The obvious necessary line.
        // A bunch of very important changes due to the name change.
    }
};

当一个人改变他的名字时,必须在System中进行一系列更改。没有这些其他的改变,一切都会崩溃。然而,很容易忘记这一点,并意外地调用Person::setName本身。如何让这成为不可能?我想到了key-pass习语,但这仍然不能阻止Person调用自己的Person::setName函数(我也不希望System成为Person的朋友)。如果这样的保护措施是不可能的,那么如何重新设计它,使这样的事故不会发生(它很可能会发生,因为我的记忆力不是那么好)?

您可以使用观察者模式。在最基本的版本中,让每个Person持有一个指向System的指针,当一个人的setName()被调用时,通知System,以便它做一些非常重要的更改:

class System; // forward declaration
class Person {
    std::string name;
    System* system;
public:
    Person(const std::string& n, System* s) : name(n), system(s) {}
    void setName(const std::string& newName);
};
class System {
public:
    void changeName (Person* person, const std::string& newName) {
        person->setName(newName);  // The obvious necessary line.
    }
    void onNameChange(Person* person) {
        // A bunch of very important changes due to the name change.
    }
};
void Person::setName(const std::string& newName) {
    name = newName;
    system->onNameChange(this); // notify the system
}