是否可以使用方法列表检查变量?

时间:2014-08-20 09:18:07

标签: java arraylist

我想将一个字符串传递给一系列方法。这些方法将检查字符串是否具有所需的所有属性。所以,如果字符串不符合一个验证方法的要求,它将返回false。

示例: 输入:" customerid = cu01"," name = someone"," phone = + 628770xxxxx"," address = somewhere",&#34 ;余额= 500000" 输出:true

另一个例子: "客户id = CU01""名称=有人""地址=某处""平衡= 200000" 输出:false(无电话号码)

是否可以像这样创建一个验证器类列表

List<Validator> val = new ArrayList<Validator>();
val.add(ValidatorA);
val.add(ValidatorB);
etc.

所以我可以检查带有验证器列表的字符串。我只是想知道,是否可以检查一个带有类似验证器列表的字符串?我之所以这样做是因为如果有一天需要添加另一个验证器会更容易。

感谢

2 个答案:

答案 0 :(得分:0)

您可以使用装饰器模式。 看看这个例子我认为它适合你的用例: http://blog.decarufel.net/2009/09/using-decorator-or-wrapper-design.html

http://sourcemaking.com/design_patterns/decorator

public abstract class ValidationObject {
    String description = "no particular";

    public String getDescription(){
        return description;
    }
}


public class Account extends ValidationObject {
    public Account(){
        description = "account";
    }
}


public class Book extends ValidationObject {
    public Book () {
        description = "book";
    }
}


public abstract class ValidationObjectDecorator extends ValidationObject {
    public abstract String getDescription();
}


public class ValidationOne extends ValidationObjectDecorator {

    private ValidationObject account;

    public ValidationOne (ValidationObject g) {
        account = g;
    }

    @Override
    public String getDescription() {
        return account.getDescription() + "+ validationOneRan";
    }

    public void validateStuff() {
        System.out.println("Big validation!");
    }
}
We can add more method like "validateOtherStuff()" to each decorator without any limitations.



public class ValidationTwo extends ValidationObjectDecorator {

    private ValidationObject book;

    public ValidationTwo(ValidationObject g) {
        book = g;
    }

    @Override
    public String getDescription() {
        return book.getDescription() + " ran validationTwo";
    }

    public void validationMethod() {
        System.out.println("Big Validation!");
    }
}


package designpatterns.decorator;

public class Main {

    public static void main(String[] args) {
        ValidationObject g1 = new Account();
        System.out.println(g1.getDescription());

        ValidationOne g2 = new Account(g1);
        System.out.println(g2.getDescription());

        ValidationTwo g3 = new Book(g2);
        System.out.println(g3.getDescription());
    }
}

答案 1 :(得分:-1)

也许您可以创建一个接口来定义一个函数,例如&#34; validate()&#34;,创建此接口的实现,然后遍历列表并应用验证函数。

示例:

public interface validator{
    public boolean validate();
}
class validateUserName{
    public boolean validate(){
         return true;
    }
}
class validatePhone{
    public boolean validate(){
          return false;
    }
}

List<Validator> list = new ArrayList<Validator>();
list.add(new validPhone());
list.add(new validUserName());


for(Validator v : list)
    v.validate();