这是两个有关如何使用Java 8功能样式以及Cyclops模式匹配和Hamcrest库来实现策略模式设计的示例。
PrintDependingOnInput方法是一种策略,该策略将根据传递的日志在System.println中显示一些消息。
AddPrefix是另一种策略,它将根据邮件内容为邮件添加前缀。
package com.marco.patternmatching;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.hamcrest.core.AllOf.allOf;
import java.util.ArrayList;
import java.util.List;
import com.aol.cyclops.matcher.builders.Matching;
public class FunctionalStrategy {
public static void main(String[] args) {
List<String> toTest = new ArrayList<>();
toTest.add("INFO everything is fine");
toTest.add("WARN something weird happened");
toTest.add("ERROR NullPointerException");
toTest.add("ERROR IOException");
toTest.stream().forEach(FunctionalStrategy::printDependingOnInput);
System.out.println("--------------------");
List<String> messages = new ArrayList<>();
messages.add("everything is fine");
messages.add("something weird happened");
messages.add("NullPointerException");
messages.add("IOException");
messages.stream().map(FunctionalStrategy::addPrefix).forEach(System.out::println);
}
public static void printDependingOnInput(String log) {
Matching
.when().isMatch(startsWith("INFO"))
.thenConsume(System.out::println)
.when().isMatch(startsWith("WARN"))
.thenConsume(message -> System.out.println("Found one warning : " + message))
.when().isMatch(allOf(startsWith("ERROR"), containsString("NullPointerException")))
.thenConsume(message -> System.err.println(message))
.when().isMatch(allOf(startsWith("ERROR"), containsString("IOException")))
.thenConsume(message -> System.err.println(message + " Retrying a couple of times"))
.match(log);
}
public static String addPrefix(String log) {
return Matching
.when().isMatch(allOf(not(containsString("Exception")), not(containsString("weird"))))
.thenApply(message -> "INFO " + message)
.when().isMatch(containsString("weird"))
.thenApply(message -> "WARN " + message)
.when().isMatch(containsString("Exception"))
.thenApply(message -> "ERROR " + message)
.match(log).get();
}
}
干净整洁;)
翻译自: https://www.javacodegeeks.com/2015/06/strategy-pattern-in-java-8.html