Last active
June 26, 2020 21:52
-
-
Save RayStarkMC/d2c806100ee242d4fc7b25d10d1a0344 to your computer and use it in GitHub Desktop.
任意のオブジェクトを戻り値thisにするパターン化するためのラッパー
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.function.BiFunction; | |
import java.util.function.Consumer; | |
import java.util.function.Function; | |
public class Pipeline<T, R> { | |
private final T value; | |
Object lastReturn; | |
private Pipeline(T value) { | |
this.value = value; | |
lastReturn = null; | |
} | |
public static <T> Pipeline<T, ?> of(T value) { | |
return new Pipeline<>(value); | |
} | |
public R lastReturn() { | |
@SuppressWarnings("unchecked") | |
R lastReturn = (R)this.lastReturn; | |
return lastReturn; | |
} | |
public Pipeline<T, R> consumeLastReturn(Consumer<? super R> consumer) { | |
consumer.accept(lastReturn()); | |
return this; | |
} | |
public Pipeline<T, ?> exec(Consumer<? super T> consumer) { | |
consumer.accept(value); | |
lastReturn = null; | |
return this; | |
} | |
public <V> Pipeline<T, V> exec(Function<? super T, ? extends V> function) { | |
lastReturn = function.apply(value); | |
@SuppressWarnings("unchecked") | |
Pipeline<T, V> ret = (Pipeline<T, V>)this; | |
return ret; | |
} | |
public <Arg1, V> Pipeline<T, V> exec(BiFunction<? super T, ? super Arg1, ? extends V> function, Arg1 arg1) { | |
lastReturn = function.apply(value, arg1); | |
@SuppressWarnings("unchecked") | |
Pipeline<T, V> ret = (Pipeline<T, V>)this; | |
return ret; | |
} | |
public static void main(String[] args) { | |
Pipeline.of("Test") | |
.exec(String::startsWith, "T").consumeLastReturn(System.out::println) | |
.exec(String::length).consumeLastReturn(System.out::println); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment