利用Lambda重构

2019-03-04  本文已影响0人  PawsUp
  1. 一个代表某个算法的接口(它是策略模式的接口)。

  2. 一个或多个该接口的具体实现,它们代表了算法的多种实现。

  3. 一个或多个使用策略对象的客户。
    例如:对输入的内容是否根据标准进行了恰当的格式化

     //声明一个函数式接口
     public interface ValidationStrategy {
          boolean execute(String s);
     } 
    //定义了该接口的一个或多个具体实现:
     public class IsAllLowerCase implements ValidationStrategy {
          public boolean execute(String s){
                return s.matches("[a-z]+");
         }
     }
     public class IsNumeric implements ValidationStrategy {
          public boolean execute(String s){
              return s.matches("\\d+");
         }
     } 
     //验证
     public class Validator{
          private final ValidationStrategy strategy;
    
          public Validator(ValidationStrategy v){
                this.strategy = v; 
          }
    
          public boolean validate(String s){
                return strategy.execute(s);
        }
     }
    
     Validator numericValidator = new Validator(new IsNumeric());
     boolean b1 = numericValidator.validate("aaaa");
     Validator lowerCaseValidator = new Validator(new IsAllLowerCase ());
     boolean b2 = lowerCaseValidator.validate("bbbb"); 
     //使用Lambda表达式
     Validator numericValidator =
            new Validator((String s) -> s.matches("[a-z]+"));
     boolean b1 = numericValidator.validate("aaaa");
     Validator lowerCaseValidator =
            new Validator((String s) -> s.matches("\\d+"));
     boolean b2 = lowerCaseValidator.validate("bbbb"); 
    

例如:定义两个对象,它们的功能是处理一些文本处理工作

public class HeaderTextProcessing extends ProcessingObject<String> {
   public String handleWork(String text){
       return "From Raoul, Mario and Alan: " + text;
   }
}
public class SpellCheckerProcessing extends ProcessingObject<String> {
   public String handleWork(String text){
       return text.replaceAll("labda", "lambda");
   }
} 

ProcessingObject<String> p1 = new HeaderTextProcessing();
ProcessingObject<String> p2 = new SpellCheckerProcessing();
p1.setSuccessor(p2);
String result = p1.handle("Aren't labdas really sexy?!!");
System.out.println(result); //打印输出“From Raoul, Marioand Alan: Aren't lambdas reallysexy?!!”

//Lambda
UnaryOperator<String> headerProcessing =
       (String text) -> "From Raoul, Mario and Alan: " + text;

UnaryOperator<String> spellCheckerProcessing =
       (String text) -> text.replaceAll("labda", "lambda");

Function<String, String> pipeline =
       headerProcessing.andThen(spellCheckerProcessing);

String result = pipeline.apply("Aren't labdas really sexy?!!");

注:
UnaryOperator<T>的函数描述符为 T -> T

利用Lambda重构之前的代码:

final static Map<String, Supplier<Product>> map = new HashMap<>();
static {
   map.put("loan", Loan::new);
   map.put("stock", Stock::new);
   map.put("bond", Bond::new);
} 
//实例化不同产品
public static Product createProduct(String name){
     Supplier<Product> p = map.get(name);
     if(p != null) return p.get();
     throw new IllegalArgumentException("No such product " + name);
} 

若需要多个参数的构造函数,则需要自定义函数式接口:

  public interface TriFunction<T, U, V, R>{
       R apply(T t, U u, V v);
  }
  Map<String, TriFunction<Integer, Integer, String, Product>> map
         = new HashMap<>(); 
上一篇下一篇

猜你喜欢

热点阅读