Skip to content

Instantly share code, notes, and snippets.

@jcdang
Created December 14, 2016 00:21
Show Gist options
  • Save jcdang/6529bbc0c5b753f248eb172b06e4ae48 to your computer and use it in GitHub Desktop.
Save jcdang/6529bbc0c5b753f248eb172b06e4ae48 to your computer and use it in GitHub Desktop.
import java.util.function.BiFunction;
public interface DeathToStrategy {
@FunctionalInterface
interface Strategy extends BiFunction<Integer, Integer, Integer>{}
static <T> void println(T arg) { System.out.println(arg); }
Strategy add = (a, b) -> a + b;
Strategy subtract = (a, b) -> a - b;
Strategy multiply = (a, b) -> a * b;
static Integer execute(Strategy callback, Integer x, Integer y) { return callback.apply(x, y); }
static void main(String[] args) {
println("Add: " + execute(add, 3, 4));
println("Subtract: " + execute(subtract, 3, 4));
println("Multiply: " + execute(multiply, 3, 4));
}
}
@jcdang
Copy link
Author

jcdang commented Dec 14, 2016

The snippet is in response to this post: http://alvinalexander.com/scala/how-scala-killed-oop-strategy-design-pattern

  1. Is a common strategy interface defined? Yes. It's named Strategy.
  2. Does there exist implementers of the strategy interface? Yes. They are add, multiply and subtract.
  3. Is there a context? Maybe? One could argue it's the class' static context.

Let's do it in Scala:

object DeathToStrategy {

  type Strategy = (Int, Int) => Int

  val add: Strategy = (a, b) => a + b
  val subtract: Strategy = (a, b) => a - b
  val multiply: Strategy = (a, b) => a * b

  def execute(callback: Strategy, x: Int, y: Int) = callback(x, y)

  def main(args: Array[String]): Unit = {
    println("Add:      " + execute(add, 3, 4))
    println("Subtract: " + execute(subtract, 3, 4))
    println("Multiply: " + execute(multiply, 3, 4))
  }
}

But wait! We didn't use the equivalent of a companion object def (static function) in the java example!

import java.util.function.BiFunction;

public interface DeathToStrategy {
    @FunctionalInterface
    interface Strategy extends BiFunction<Integer, Integer, Integer>{}
    static <T> void println(T arg) { System.out.println(arg); }

    static Integer add(Integer a, Integer b) { return a + b; }
    static Integer subtract(Integer a, Integer b) { return a - b; }
    static Integer multiply(Integer a, Integer b) { return a * b; }

    static Integer execute(Strategy callback, Integer x, Integer y) { return callback.apply(x, y); }

    static void main(String[] args) {
        println("Add:      " + execute(DeathToStrategy::add, 3, 4));
        println("Subtract: " + execute(DeathToStrategy::subtract, 3, 4));
        println("Multiply: " + execute(DeathToStrategy::multiply, 3, 4));
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment