zoukankan      html  css  js  c++  java
  • 设计模式:visitor模式

    核心:将数据结构和数据的处理分开

    注意:注意函数的参数传递和调用关系

    例子:

    class Element;
    
    class Visitor
    {
    public:
        virtual void Visit(Element* element) = 0;
    };
    
    class Element
    {
    public:
    	virtual void accept(Visitor* visitor)
    	{
    		visitor->Visit(this);
    	}
    };
    
    class Book: public Element
    {
    	string name;
    	int price;
    public:
    	Book(string name, int price)
    	{
    		this->name = name;
    		this->price = price;
    	}
    	
    	string getName()
    	{
    		return name;
    	}
    	
    	int getPrice()
    	{
    		return price;
    	}
    };
    
    class BookVisitor: public Visitor
    {
    public:
    	void Visit(Element* element)
    	{
    		Book* book = dynamic_cast<Book*>(element);
    		cout << "book: name = " << book->getName() << "  price = " << book->getPrice() << endl;
    	}
    };
    
    int main() 
    {
    	Book* b = new Book("设计模式", 50);
    	BookVisitor* bv = new BookVisitor();
    	b->accept(bv);
    	
    	return 0;
    }
  • 相关阅读:
    Tinkoff Challenge
    Tinkoff Challenge
    Tinkoff Challenge
    Tinkoff Challenge
    整体二分
    树链剖分+LCT
    上下界网络流
    莫队
    可并堆
    bzoj_1033: [ZJOI2008]杀蚂蚁antbuster
  • 原文地址:https://www.cnblogs.com/chusiyong/p/11433643.html
Copyright © 2011-2022 走看看