Java企业教程系列

使用Java8的Lambda实现策略模式

   策略Strategy模式是GoF设计模式中的一种。定义了一组算法,彼此封装,客户端调用能够独立地使用它们。在这里我们使用Java 8的Lambda表达式实现策略模式。

我们首先看看传统Java实现策略模式案例,假设一个接口为策略:

interface Strategy{

  public void performTask();

}

这个策略有两个实现:

class LazyStratgey implements Strategy{

  @Override

  public void performTask() {

    System.out.println("Perform task a day before deadline!");

  }

}

 

class ActiveStratgey implements Strategy{

  @Override

  public void performTask() {

    System.out.println("Perform task now!");

  }

}

策略模式的调用:

public class StartegyPatternOldWay {

 

  public static void main(String[] args) {

    List<Strategy> strategies =

        Arrays.asList(

          new LazyStratgey(),

          new ActiveStratgey()

        );

 

    for(Strategy stg : strategies){

      stg.performTask();

    }

  }

}

输出:

Perform task a day before deadline!
Perform task now!

以上是传统Java实现的,下面我们使用Java 8以后提供Lambda表达式实现策略模式:

使用Lmabda我们就不需要为策略接口创建不同的实现子类了,使用lambda表达式替代。

public class StrategyPatternOnSteroids {

  public static void main(String[] args) {

    System.out.println("Strategy pattern on Steroids");

    List<Strategy> strategies =

      Arrays.asList(

        () -> {System.out.println("Perform task a day before deadline!");},

        () -> {System.out.println("Perform task now!");}

      );

    strategies.forEach((elem) -> elem.performTask());

  }

}

输出为:

Strategy pattern on Steroids
Perform task a day before deadline!
Perform task now!


另外一个案例 :

有一个计算接口:

interface Computation<T> {

  public T compute(T n, T m);

}

计算接口下有三个子类,IntSum – 返回两个整数的总和,, IntDifference – 返回两个整数的差值,IntProduct – 返回两个整数的乘积。传统Java需要实现三个子类如下:

class IntSum implements Computation<Integer> {

  @Override

  public Integer compute(Integer n, Integer m) {

    return n + m;

  }

}

 

class IntProduct implements Computation<Integer> {

  @Override

  public Integer compute(Integer n, Integer m) {

    return n * m;

  }

}

 

class IntDifference implements Computation<Integer> {

  @Override

  public Integer compute(Integer n, Integer m) {

    return n - m;

  }

}

调用客户端代码需要对这三个子类进行new创建:

public class AnotherStrategyPattern {

 

  public static void main(String[] args) {

    List<Computation> computations =

        Arrays.asList(

          new IntSum(),

          new IntDifference(),

          new IntProduct()

        );

 

    for (Computation comp : computations) {

      System.out.println(comp.compute(10, 4));

    }

  }

}

而使用Lambda表达式则不必实现创建三个子类。直接使用Lambda表达式替代即可:

public class AnotherStrategyPatternWithLambdas {

  public static void main(String[] args) {

    List<Computation<Integer>> computations =

          Arrays.asList(

              (n, m)-> { return n+m; },

              (n, m)-> { return n*m; },

              (n, m)-> { return n-m; }

          );

    computations.forEach((comp) -> System.out.println(comp.compute(10, 4)));

  }

}

 

Closure Lambda和Monad

Java 8教程

函数编程