命令模式与访客模式
允许访问者修改接收者的状态通常是可以接受的,还是应该改为命令模式?
Is it generally acceptable to allow a Visitor to modify state of the Receiver, or should that be a Command pattern instead?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
访问者模式的目的是允许将新操作添加到类层次结构中,而无需修改该层次结构。我从未见过有人建议只接受只读操作。唯一的限制是添加的操作只能使用类层次结构的公共接口。
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.
我认为你不能笼统地声明修改任何东西的状态是好还是坏。我认为只要不影响访问逻辑本身,修改状态就可以了。例如,您可以编写一个访问者来访问文件夹结构下的所有文件并将文件名重命名为大写。
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.
Microsoft 的访问者修改接收器的示例是 ExpressionVisitor 。 ExpressionVisitor 类的目的是修改表达式树。所以我猜微软至少认为这是可以接受的。
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.
每种模式都有自己的优点、缺点和用例。
您可以使用
Command
模式来解耦调用者和调用者。命令接收者
实现回调机制
实现撤消和重做功能
维护命令历史记录
使用
Visitor
以下场景中的模式:相关帖子:
使用命令设计模式
我什么时候应该使用访客设计模式?
Each pattern has it's own pros, cons and use cases.
You can use
Command
pattern toDecouple the invoker & receiver of command
Implement callback mechanism
Implement undo and redo functionality
Maintain a history of commands
Use
Visitor
pattern in below scenarios:Related posts:
Using Command Design pattern
When should I use the Visitor Design Pattern?