java - 用于验证文件的设计模式

标签 java design-patterns validation file-upload

我们必须验证包含各种配置参数的 CSV 文件。是否有任何标准设计模式来执行此类验证。

更多详情:

  • 有不同类型的记录——每种都有自己的验证逻辑
  • 某些记录交叉引用其他记录
  • 记录顺序有规律
  • 有关于重复记录资格的规则
  • 等等

最佳答案

您可以使用 Strategy用于验证记录的模式。有一个抽象基类来表示一个记录,你可以使用 Factory Method , 或 Simple Factory 来创建各种 Record 类型的具体实例。
您的规范不完整。这是实现策略模式的代码示例 对你的记录有一个简单的假设。

interface Validator {
     // since it is not clear what are the attributes that matter for a record, 
     // this takes an instance of Record. 
     // Modify to accept relevant attribures of Record
     public boolean validate (Record r);
 }

 class ConcreteValidator implements Validator {
      // implements a validation logic
 }

// implements Comparable so that it can be used in rules that compare Records
abstract class Record implements Comparable<Record> {
    protected Validator v;
    abstract void setValidator(Validator v);
    public boolean isValid() {
        return v.validate(this);
    }
}

class ConcreteRecord extends Record {
   // alternatively accept a Validaor during the construction itself 
   // by providing a constructor that accepts a type of Validator
   // i.e. ConcreteRecord(Validator v) ...
    void setValidator(Validator v) {
        this.v = v;
    }

    // implementation of method from Comparable Interface
    public int compareTo(final Record o) {... }
}

public class Test {
    public static void main(String[] args) {
        // Store the read in Records in a List (allows duplicates)
        List<Record> recordList = new ArrayList<Record>();
        // this is simplistic. Your Record creation mode might be 
        // more complex, And you can use a Factory Method 
        // (or Simple Factory) for creation of  ConcreteRecord
        Record r = new ConcreteRecord();
        r.setValidtor(new ConcretedValidator());
        if (r.isValid()) {
            // store only valid records
            recordList.add(r);
        }

       // do further processing of Records stored in recordList
    }

}

关于java - 用于验证文件的设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2061396/

相关文章:

java - 为什么bark方法无法调用

java - Simpledateformat - 为什么 Calendar.MONTH 错误地生成 16 年 1 月的上个月值(即 Dec-2015)?

java - 如何为返回带有泛型的函数的方法声明泛型

java - 编程作业;构造函数 -> 表达式开头无效 + 分号困扰

php - 代码注释 - 是否应该对使用的设计模式进行注释

design-patterns - MVVM View 模型和异步数据初始化

javascript - 独立于编程语言的模型验证

c# - 具有 100 个以上属性的类的设计模式

javascript - JQuery 验证消息奇怪地出现在两个单选按钮之间

ASP.NET - 在一页上单独验证两个表单?