c++设计模式访问者模式

访问者模式

#include 
#include 

using namespace std;

class Visitor;

class Cat;
class Dog;

class Visitor {
public:
    virtual void visit(Cat* cat) = 0;
    virtual void visit(Dog* dog) = 0;
};


template<typename Derive>
class VisitingBase {
public:
     void accept(Visitor* v) {
         v->visit((Derive*)(this));
     }
};


class Cat : public VisitingBase<Cat> {
public:
    string name;
    int age;

    int getAge() const {
        return age;
    }

    string getName() const {
        return name;
    }

    void miaomiao() {
        cout << "miaomiao" << endl;
    }

    void eat() {
        cout << "cat is starting to eat" << endl;
    }
};


class Dog : public VisitingBase<Dog> {
public:
    string name;
    int age;

    int getAge() const {
        return age;
    }

    string getName() const {
        return name;
    }

    void wangwangwang() {
        cout << "wangwangwang" << endl;
    }

    void eat() {
        cout << "dog is starting to eat" << endl;
    }
};


class PetKeeper : public Visitor {
public:
    void visit(Cat* cat) override {
        cat->miaomiao();
        cat->eat();
    }

    void visit(Dog *dog) override {
        dog->wangwangwang();
        dog->eat();
    }
};

class DescriptitionVisitor : public Visitor {
public:
    void visit(Cat *cat) override {
        cout << "\n----------------------descriptition---------------------" << endl;
        cout << "name : " << cat->getName() << endl;
        cout << "age: " << cat->getAge() << endl;
    }

    void visit(Dog *dog) override {
        cout << "\n----------------------descriptition---------------------" << endl;
        cout << "name : " << dog->getName() << endl;
        cout << "age: " << dog->getAge() << endl;
    }
};

int main() {
    DescriptitionVisitor dv;
    PetKeeper petKeeper;

    Cat* cat = new Cat{.name="flash", .age=2};

    cat->accept(&dv);
    cat->accept(&petKeeper);


    Dog* dog = new Dog{.name="huang", .age=4};
    dog->accept(&dv);
    dog->accept(&petKeeper);
}

你可能感兴趣的:(c++,设计模式,访问者模式)