-
-
Save sayems/7c64197a43a2c52544bb to your computer and use it in GitHub Desktop.
This file contains hidden or 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.List; | |
| import java.util.ArrayList; | |
| import java.util.Arrays; | |
| import java.util.function.Supplier; | |
| import java.util.function.UnaryOperator; | |
| class Person | |
| { | |
| String name; | |
| int age; | |
| public String toString(){ | |
| return String.format("%s, %d", this.name, this.age); | |
| } | |
| } | |
| class Developer extends Person | |
| { | |
| String language; | |
| public String toString(){ | |
| return String.format("%s, %s", super.toString(), this.language); | |
| } | |
| } | |
| public class Builder<T> | |
| { | |
| @FunctionalInterface | |
| public interface Lambda<T> | |
| { | |
| public T build(T t); | |
| } | |
| private final Supplier<T> supplier; | |
| private Lambda<T> lambda; | |
| public Builder(Supplier<T> supplier) | |
| { | |
| this.supplier = supplier; | |
| } | |
| public Builder<T> lambda(Lambda<T> lambda){ | |
| this.lambda = lambda; | |
| return this; | |
| } | |
| public T build(){ | |
| return this.lambda.build(this.supplier.get()); | |
| } | |
| public T build(UnaryOperator<T> unary){ | |
| return unary.apply(this.supplier.get()); | |
| } | |
| public static void main(String... args) | |
| { | |
| Builder<Person> personBuilder = new Builder<Person>(Person::new); | |
| Person person = personBuilder.lambda( p -> { p.name = "Markos"; p.age = 33; return p; } ).build(); | |
| System.out.println(person); | |
| Builder<Developer> developerBuilder = new Builder<Developer>(Developer::new); | |
| Developer developer = developerBuilder.lambda( d -> { d.name = "Markos"; d.age = 33; d.language = "Java"; return d; } ).build(); | |
| System.out.println(developer); | |
| Builder<List<String>> listBuilder = new Builder<List<String>>(ArrayList::new); | |
| List<String> strings = listBuilder.build( l -> { l.add("foo"); l.add("bar"); return l; } ); | |
| //strings.forEach( System.out::println ); | |
| for(String s : strings){ | |
| System.out.println(s); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment