Created
November 27, 2020 06:02
-
-
Save drem-darios/82254a91c1beddd2777073898170f71c to your computer and use it in GitHub Desktop.
This demonstrates the Decorator pattern using functional programming
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.awt.*; | |
import java.util.function.Consumer; | |
import java.util.function.Function; | |
import java.util.stream.Stream; | |
public class Camera { | |
private Function<Color, Color> filter; | |
public Camera(){ | |
setFilters(); | |
} | |
public void setFilters(final Function<Color, Color>... filters) { | |
// orElseGet(Function::identity) is the same as orElse(color -> color). This is to say return the color that was passed into the function | |
this.filter = Stream.of(filters) | |
.reduce((filter, next) -> filter.compose(next)) | |
.orElseGet(Function::identity); | |
} | |
public Color capture(final Color inputColor) { | |
final Color processedColor = filter.apply(inputColor); | |
// ... more processing of color... | |
return processedColor; | |
} | |
public static void main(String[] args) { | |
final Camera camera = new Camera(); | |
final Consumer<String> printCaptured = (filterInfo) -> System.out.println(String.format("with %s: %s", filterInfo, camera.capture(new Color(200, 100, 200)))); | |
printCaptured.accept("no filter"); | |
camera.setFilters(Color::brighter); | |
printCaptured.accept("brighter filter"); | |
camera.setFilters(Color::darker); | |
printCaptured.accept("darker filter"); | |
camera.setFilters(Color::brighter, Color::darker); | |
printCaptured.accept("brighter & darker filter"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment