问题描述
我正在根据以下假设编写一些验证代码:
I am in the process of writing some validation code based on these assumptions:
- 验证代码必须在外部类中
- 即没有数据类包含它自己的验证
- Validation code must be in an external class
- i.e. no data class contains it's own validation
- 例如仅验证语法;针对数据库查找进行验证;验证是否重复;等等
- 例如输出单个错误消息;输出所有验证错误的列表;类似,但格式为JSON,并包含错误代码;等等
哪种OO设计模式组合最能解决此问题?工厂可能是获得特定验证器的好方法,但是他们的更好方法是吗?
What combination of OO design patterns are best to solve this? A factory might be a good way to get a specific validator, but are their better approaches?
推荐答案
一种尺寸并不适合所有尺寸!简单点吧!
为验证器提供通用的方法/接口,以输出数据,对警告进行分类,对过滤器/过程提出的警告进行多次.不要自己创建任何复杂的验证方式,至少在编写一些现实生活验证器之前不要这样做.
Provide validators with common methods/interface to output data, categorize warnings, filter/process warnings raised more than once. Do not create any sophisticated way of validation itself, at least not before writing a few real life validators.
移开方式,让验证者执行他们应该做的事情:
Move out of the way and let the validators do what they are supposed to do:
for validator in all_validators: validator.validate(model)
这篇关于用于验证的OO设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!