设计模式: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;
}
posted @ 2019-08-30 10:38  Yong_无止境  阅读(178)  评论(0编辑  收藏  举报