#include<iostream> #include <list> using namespace std; class Apple; class Book; //抽象访问者 class Visitor { protected: string name; public: void setName(string name) { this->name = name; } string getname() { return name; } virtual void visit(Apple *apple)=0; virtual void visit(Book *book)=0; }; //抽象元素 class Product { public: virtual void accept(Visitor *visitor)=0; }; //具体元素 class Apple :public Product { public: void accept(Visitor *visitor) { visitor->visit(this); } }; //具体元素 class Book :public Product { public: void accept(Visitor *visitor) { visitor->visit(this); } }; //对象结构 class BuyBasket { private: list< Product*> product; public: void accept(Visitor* visitor) { for (std::list<Product*>::iterator it = product.begin(); it != product.end(); ++it) (*it)->accept(visitor); } void addProduct(Product* product2) { product.push_back(product2); } void removeProduct(Product* product2) { product.remove(product2); } }; class Saler :public Visitor { public: void visit(Apple *apple) { cout << "收银员" <<name.c_str() << "给苹果过秤,然后计算其价格。" << endl; } void visit(Book *book) { cout << "收银员" << name.c_str() << "直接计算书的价格。" << endl; } }; class Customer :public Visitor { public: void visit(Apple *apple) { cout << "顾客" << name.c_str() << "选苹果。" << endl; } void visit(Book *book) { cout << "顾客" << name.c_str() << "买书。" << endl; } }; class Pack { private: list< Product*> product; public: void accept(Visitor* visitor) { for (std::list<Product*>::iterator it = product.begin(); it != product.end(); ++it) (*it)->accept(visitor); } void addProduct(Product* product2) { product.push_back(product2); } void removeProduct(Product* product2) { product.remove(product2); } }; class Packer :public Visitor { public: void visit(Apple *apple) { cout << "打包员" << name.c_str() << "给购物车中的苹果进行打包。" << endl; } void visit(Book *book) { cout << "打包员" << name.c_str() << "给购物车中的书本进行打包。" << endl; } }; int main() { Product *b1 = new Book(); Product *a1 = new Apple(); Visitor* visitor1 = new Customer(); Visitor* visitor2 = new Packer(); Visitor* visitor3 = new Saler(); BuyBasket *basket = new BuyBasket(); basket->addProduct(b1); basket->addProduct(a1); visitor1->setName("张三"); visitor2->setName("李四"); visitor3->setName("王五"); basket->accept(visitor1); basket->accept(visitor3); basket->accept(visitor2); delete a1, b1,visitor1, visitor2, visitor3; return 0; }
标签:product,visitor,void,accept,class,模式,public,访问者 From: https://www.cnblogs.com/qiuyutingyyds/p/17001606.html