实验 25:访问者模式
在我们课堂上的“购物车”的例子中,增加一个新的访问者:打包员,负责对购物车中货物装包。
C++源码:
#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("小A"); visitor2->setName("小B"); visitor3->setName("小C"); basket->accept(visitor1); basket->accept(visitor3); basket->accept(visitor2); delete a1, b1,visitor1, visitor2, visitor3; return 0; }