Skip to content

Commit f736ff8

Browse files
authored
Create decorator using lambda expression (#37)
1 parent fc84af0 commit f736ff8

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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+
}

0 commit comments

Comments
 (0)