File tree Expand file tree Collapse file tree 2 files changed +51
-0
lines changed
main/java/pl/mperor/lab/java/design/pattern/structural/decorator
test/java/pl/mperor/lab/java/design/pattern/structural/decorator Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ package pl .mperor .lab .java .design .pattern .structural .decorator ;
2+
3+ import java .util .Arrays ;
4+ import java .util .function .UnaryOperator ;
5+
6+ @ FunctionalInterface
7+ public interface TextProcessor extends UnaryOperator <String > {
8+
9+ default TextProcessor chain (TextProcessor after ) {
10+ return input -> after .apply (this .apply (input ));
11+ }
12+
13+ static TextProcessor identity () {
14+ return s -> s ;
15+ }
16+
17+ static TextProcessor of (TextProcessor processor ) {
18+ return processor ;
19+ }
20+
21+ static TextProcessor of (TextProcessor ... processors ) {
22+ return Arrays .stream (processors )
23+ .reduce (TextProcessor .identity (), TextProcessor ::chain );
24+ }
25+ }
Original file line number Diff line number Diff line change 1+ package pl .mperor .lab .java .design .pattern .structural .decorator ;
2+
3+ import org .junit .jupiter .api .Assertions ;
4+ import org .junit .jupiter .api .Test ;
5+
6+ public class TextProcessorTest {
7+
8+ @ Test
9+ public void shouldAllowToCreateTextProcessorAsChainOfFunctions () {
10+ Assertions .assertEquals ("prefix@Hello World@suffix" ,
11+ TextProcessor .of (String ::strip )
12+ .chain (s -> "prefix" + s )
13+ .chain (s -> s + "suffix" )
14+ .apply (" @Hello World@" )
15+ );
16+
17+ Assertions .assertEquals ("HEX" ,
18+ TextProcessor .of (
19+ String ::toUpperCase ,
20+ s -> s .replace ("L" , "X" ),
21+ s -> s .substring (0 , 3 )
22+ ).apply ("Hello World" )
23+ );
24+ }
25+
26+ }
You can’t perform that action at this time.
0 commit comments