设计模式之策略模式
1、Java8书籍策略模式
1.1、ValidationStrategy
package com.chenheng.strategy;
/**
* @author: chenheng@ovopark.com
* @create: 2021-12-01 16:55
* @description: Java8书籍策略模式
**/
public interface ValidationStrategy {
boolean execute(String s);
}
1.2、IsAllLowerCase
package com.chenheng.strategy;
/**
* @author: chenheng@ovopark.com
* @create: 2021-12-01 16:56
* @description:
**/
public class IsAllLowerCase implements ValidationStrategy{
@Override
public boolean execute(String s) {
return s.matches("[a-z]+");
}
}
1.3、IsNumeric
package com.chenheng.strategy;
/**
* @author: chenheng@ovopark.com
* @create: 2021-12-01 16:56
* @description:
**/
public class IsNumeric implements ValidationStrategy{
@Override
public boolean execute(String s) {
return s.matches("\\d+");
}
}
1.4、Validator
package com.chenheng.strategy;
/**
* @author: chenheng@ovopark.com
* @create: 2021-12-01 17:23
* @description: 策略模式
**/
public class Validator {
private final ValidationStrategy strategy;
public Validator(ValidationStrategy strategy) {
this.strategy = strategy;
}
public boolean validate(String s){
return strategy.execute(s);
}
}
1.5、StrategyClient
package com.chenheng.strategy;
/**
* @author: chenheng@ovopark.com
* @create: 2021-12-03 09:21
* @description:
**/
public class StrategyClient {
public static void main(String[] args) {
Validator numberValidator = new Validator(new IsNumeric());
boolean numberValidate = numberValidator.validate("aaa");
System.out.println("numberValidate->"+numberValidate);
Validator allLowerCaseValidator = new Validator(new IsAllLowerCase());
boolean lowerCaseValidate = allLowerCaseValidator.validate("aaa");
System.out.println("lowerCaseValidate->"+lowerCaseValidate);
System.out.println("Java8 lambda");
Validator numberV = new Validator(s -> s.matches("\\d+"));
boolean flag = numberV.validate("aaa");
System.out.println("flag->"+flag);
Validator lowerCaseV = new Validator(s -> s.matches("[a-z]+"));
boolean flag1 = lowerCaseV.validate("123");
System.out.println("flag1->"+flag1);
}
}
2、菜鸟教程-策略模式
1、策略模式