Command Pattern vs. Visitor Pattern

て烟熏妆下的殇ゞ 提交于 2019-12-07 00:37:06

问题


Is it generally acceptable to allow a Visitor to modify state of the Receiver, or should that be a Command pattern instead?


回答1:


The purpose of the visitor pattern is to allow new operations to be added to a class heirarchy without modification to that heirarchy. I've never seen anyone suggesting that only read-only operations are acceptable. The only limitation is that the added operations should only use the public interface of the class heirarchy.




回答2:


I don't think you can make a blanket statement whether it's good or bad to modify state of anything. I would think it's ok to modify the states as long as it does not affect the visiting logic itself. For example, you might write a visitor that visits all files under folder structure and renames the file name to upper case.




回答3:


Microsoft's example of a visitor modifying the receiver is the ExpressionVisitor. The purpose of the ExpressionVisitor class is to modify an Expression tree. So I guess Microsoft at least thinks it's acceptable.




回答4:


Each pattern has it's own pros, cons and use cases.

You can use Command pattern to

  1. Decouple the invoker & receiver of command

  2. Implement callback mechanism

  3. Implement undo and redo functionality

  4. Maintain a history of commands

Use Visitor pattern in below scenarios:

  1. Similar operations have to be performed on objects of different types grouped in a structure
  2. You need to execute many distinct and unrelated operations. It separates Operation from objects Structure
  3. New Operations have to be added without change in object structure

Related posts:

Using Command Design pattern

When should I use the Visitor Design Pattern?



来源:https://stackoverflow.com/questions/2857880/command-pattern-vs-visitor-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!