Java: strategy and observer with interfaces and lambdas
The strategy pattern puts interchangeable behaviors behind one interface, so the caller picks which behavior to use and the code that uses it does not change. A functional interface with one method can be implemented with a lambda, which keeps each strategy short.
Java
import java.util.*;
import java.util.function.*;
class Main {
interface Discount {
double apply(double price);
}
static class EventBus {
private final List<Consumer<String>> listeners = new ArrayList<>();
void subscribe(Consumer<String> listener) {
listeners.add(listener);
}
void publish(String event) {
for (Consumer<String> listener : listeners) {
listener.accept(event);
}
}
}
public static void main(String[] args) {
Discount none = price -> price;
Discount tenPercent = price -> price * 0.9;
Discount[] plans = {none, tenPercent};
for (int i = 0; i < plans.length; i++) {
System.out.println("plan " + i + ": " + plans[i].apply(100.0));
}
EventBus bus = new EventBus();
List<String> log = new ArrayList<>();
bus.subscribe(log::add);
bus.subscribe(event -> System.out.println("got " + event));
bus.publish("order_placed");
System.out.println(log);
}
}