<( ̄︶ ̄)小小程序员

<( ̄︶ ̄)小小程序员

#include <iostream>
#include <string>
#include <memory>
using namespace std;

class AbstractMember; // 前向声明

// 行为基类
class AbstractAction {
public:
    virtual void maleDoing(AbstractMember* member) = 0;
    virtual void femaleDoing(AbstractMember* member) = 0;
    virtual ~AbstractAction() {}
};

class Anger : public AbstractAction {
public:
    void fight() {
        cout << "I want to fight" << endl;
    }

    void warning() {
        cout << "I am warning" << endl;
    }

    void maleDoing(AbstractMember* member) override;
    void femaleDoing(AbstractMember* member) override;
};

class Horror : public AbstractAction {
public:
    void help() {
        cout << "I need help" << endl;
    }

    void think() {
        cout << "I am thinking" << endl;
    }

    void maleDoing(AbstractMember* member) override;
    void femaleDoing(AbstractMember* member) override;
};

// 抽象成员基类
class AbstractMember {
public:
    virtual void accept(AbstractAction* action) = 0;
    virtual ~AbstractMember() {}

    AbstractMember(string name) : mName(name) {}
    string getName() {
        return mName;
    }
protected:
    string mName;
};

class maleMember : public AbstractMember {
public:
    using AbstractMember::AbstractMember;
    void accept(AbstractAction* action) override {
        action->maleDoing(this);
    }
};

class femaleMember : public AbstractMember {
public:
    using AbstractMember::AbstractMember;
    void accept(AbstractAction* action) override {
        action->femaleDoing(this);
    }
};

// Anger and Horror methods implementation
void Anger::maleDoing(AbstractMember* member) {
    cout << "I am " << member->getName() << endl;
    fight();
}

void Anger::femaleDoing(AbstractMember* member) {
    cout << "I am " << member->getName() << endl;
    warning();
}

void Horror::maleDoing(AbstractMember* member) {
    cout << "I am " << member->getName() << endl;
    think();
}

void Horror::femaleDoing(AbstractMember* member) {
    cout << "I am " << member->getName() << endl;
    help();
}

int main() {
    unique_ptr<AbstractMember> maleAnger = make_unique<maleMember>("Luffy");
    unique_ptr<AbstractAction> angerAction = make_unique<Anger>();
    maleAnger->accept(angerAction.get());

    unique_ptr<AbstractMember> maleHorror = make_unique<maleMember>("Zoro");
    unique_ptr<AbstractAction> horrorAction = make_unique<Horror>();
    maleHorror->accept(horrorAction.get());

    unique_ptr<AbstractMember> femaleAnger = make_unique<femaleMember>("Nami");
    femaleAnger->accept(angerAction.get());

    unique_ptr<AbstractMember> femaleHorro = make_unique<femaleMember>("luobi");
    femaleHorro->accept(horrorAction.get());
}

c++设计模式-->访问者模式-LMLPHP

05-24 23:58