All functions will take in string and return void
在这种情况下,您可以使用Consumer< String>界面和创建工厂如下:
public class ConsumerFactory {
private static final Map> consumers = new HashMap<>();
public static Consumer getConsumer(String key) {
if (key != null && consumers.containsKey(key)) {
return consumers.get(key);
}
throw new NoSuchElementException(key);
}
public static Consumer addConsumer(String key, Consumer value) {
return consumers.put(key, value);
}
}
ConsumerFactory.addConsumer("print", System.out::println);
ConsumerFactory.getConsumer("print").accept("Hello");