针对条件的访问者模式?
我似乎没有在访问者模式的使用场景中找到这一点(或者也许我不明白)。 它也没有等级之分。
让我们使用一个身份验证示例。 UserAuthenticator 验证用户提供的凭据。 它返回一个结果对象。 结果对象包含身份验证的结果:身份验证成功、由于未找到用户名而未成功、由于使用了非法字符而未成功等。客户端代码可以诉诸条件来处理此问题。 用伪代码来说:
AuthResult = Userauthenticator.authenticate(Username, Password)
if AuthResult.isAuthenticated: do something
else if AuthResult.AuthFailedBecauseUsernameNotFound: do something else
else if etc...
访客模式适合这里吗? :
Authresult.acceptVisitor(AuthVisitor)
Authresult 然后根据结果调用 AuthVisitor 上的方法:
AuthVisitor.handleNotAuthenticatedBecauseUsernameNotFound
I don't seem to find this in usage scenarios for the visitor pattern (or maybe I don't get it). It's also not hierarchical.
Let's use an authentication example. A UserAuthenticator authenticates credentials given by a user. It returns a result object. The result object contains the result of the authentication: authentication succeeded, not succeeded because username was not found, not succeeded because illegal characters were used etc. Client code may resort to conditionals to handle this.
In pseudocode:
AuthResult = Userauthenticator.authenticate(Username, Password)
if AuthResult.isAuthenticated: do something
else if AuthResult.AuthFailedBecauseUsernameNotFound: do something else
else if etc...
Would a visitor pattern fit here? :
Authresult.acceptVisitor(AuthVisitor)
Authresult then calls a method on AuthVisitor depending on the result :
AuthVisitor.handleNotAuthenticatedBecauseUsernameNotFound
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您的数据不会随着您的行为而快速变化时,访问者是一个有价值的设计。 一个典型的例子是解析树:
我不认为访问者在这里是一个有价值的解决方案,因为每次添加 AuthResult 的子类都会破坏访问者。
Visitor是关于双重调度的交易封装。
您可以尝试类似的方法:
一些处理程序策略:
并且:
现在您可以将错误处理和操作封装在您的处理程序中,这比访问者的代码少得多,因为您实际上不需要双重分派。
Visitor is a valuable design when your data doesn't change fast as your behaviour. A typical example is with a parse tree:
I don't think that a Visitor is a valuable solution here, since each time you add a subclass of AuthResult you break your visitor.
Visitor is about trading encapsulation with double dispatch.
You can try a similar approach:
some Handler stategies:
and:
now you can encapsulate error handling and operatorion in your
Handler
s that is much less code than Visitor since you don't really need double dispatch here.我不建议将模式用于非其目的的用途。
访问者模式的意图是:
如果您计划执行各种身份验证方法,则此解决方案将很有用,但如果您计划只执行一种方法,则无论如何都必须使用条件。
I would not recommend using patterns for intent they were not made for.
The intents of the visitor patterns are:
This solution would be useful if you had planned to do various authentification methods, but if you plan on only doing one, you'll have to use conditionals anyway.