/**
* 策略模式代表了一类算法的通用解决方案,可以在运行时选择那种方案
*/
public interface Strategy {
boolean execute(String s);
}
class IsAllLowerCase implements Strategy{
@Override
public boolean execute(String s) {
return s.matches("[a-z]+");
}
}
class IsNumric implements Strategy{
@Override
public boolean execute(String s) {
return s.matches("\\d+");
}
}
public class Validator {
private final Strategy strategy;
public Validator(Strategy strategy) {
this.strategy = strategy;
}
public boolean validate(String s){
return strategy.execute(s);
}
}
import org.junit.Test;
import static org.junit.Assert.*;
public class ValidatorTest {
@Test
public void validate() {
///java8以前的策略模式实现
Validator validator = new Validator(new IsNumric());
System.out.println(validator.validate("aaaa"));
///使用Lambda表达式
Validator numericValidate = new Validator((s)->s.matches("\\d+"));
System.out.println(numericValidate.validate("89"));
Validator lowerValidate = new Validator((s)->s.matches("[a-z]+"));
System.out.println(lowerValidate.validate("addd"));
}
}