- Source: cipher
- ciphermagic.cn/java8-builder.html
Programmers often encounter soul-searching questions: Do you have a partner?
No, but I can get a new one!
public class GirlFriend { private String name; private int age; // Omit getter & setter... public static void main(String[] args) { GirlFriend myGirlFriend = new GirlFriend(); MyGirlFriend. Elegantly-named setName (" small beautiful "); myGirlFriend.setAge(18); }}
No problem, brother! But what if the object has too many attributes?
public class GirlFriend { private String name; private int age; private int bust; private int waist; private int hips; private List<String> hobby; private String birthday; private String address; private String mobile; private String email; private String hairColor; private Map<String, String> gift; // Wait... // Omit getter & setter... public static void main(String[] args) { GirlFriend myGirlFriend = new GirlFriend(); MyGirlFriend. Elegantly-named setName (" small beautiful "); myGirlFriend.setAge(18); myGirlFriend.setBust(33); myGirlFriend.setWaist(23); myGirlFriend.setHips(33); myGirlFriend.setBirthday("2001-10-26"); MyGirlfriend.setAddress (" Shanghai Pudong "); myGirlFriend.setMobile("18688888888"); myGirlFriend.setEmail("[email protected]"); MyGirlFriend. SetHairColor (" light ribbon point micro volume "); List<String> hobby = new ArrayList<>(); Hobby. Add (" shopping "); Hobby. Add (" shopping "); Hobby. add(" buy something "); myGirlFriend.setHobby(hobby); Map<String, String> gift = new HashMap<>(); Put (" Valentine's Day ", "LBR 1912 Queen's Age "); Put (" birthday gift ", "Dior flame blue gold "); Put (" Memorial Day Gift ", "Armani Red Tube Lip Glaze "); myGirlFriend.setGift(gift); // Wait... }}
—
Girlfriend {name=' 2001-10-26', age=18, bust=33, waist=23, hips=33, hobby=[shopping, shopping, shopping], birthday='2001-10-26', Address =' Shanghai Pudong ', Mobile ='18688888888', Email ='[email protected]', hairColor=' light brown with little curls', Gift ={Valentine's Day Gift =LBR 1912 Queen's Age, Birthday gift = Dior flame blue gold, anniversary gift = Armani red tube lip glaze}}
Girlfriend is beautiful, but it’s hard to write.
Disadvantages: Separating instantiation from setting properties is hard to maintain; The variable name is written repeatedly.
Don’t panic, see the magic weapon ~
Here will not introduce other Builder implementation, directly dedicated to the most practical general Builder:
Applies to all classes, no modification of the original class is required, and Lombok plug-in support is not required.
First look at the posture:
Public Class Girlfriend {// Girlfriend is the best friend. // Omit getter & setter... // For demonstration purposes, Public void addHobby(String Hobby) {this.Hobby = optional.ofNullable (this.Hobby).oRelse (new ArrayList<>()); this.hobby.add(hobby); } public void addGift(String day, String gift) { this.gift = Optional.ofNullable(this.gift).orElse(new HashMap<>()); this.gift.put(day, gift); } public void setVitalStatistics(int bust, int waist, int hips) { this.bust = bust; this.waist = waist; this.hips = hips; } public static void main(String[] args) { GirlFriend myGirlFriend = Builder.of(GirlFriend::new) With (GirlFriend: : elegantly-named setName, "small beautiful"), with (GirlFriend: : setAge, 18) with (GirlFriend: : setVitalStatistics, 33, 23, With (Girlfriend ::setBirthday, "2001-10-26"). With (Girlfriend ::setAddress, "Shanghai ::setAddress "). "18688888888") .with(GirlFriend::setEmail, "[email protected]") .with(GirlFriend::setHairColor, "Light brown with slight curls "). With (Girlfriend :: AddHobby," Shopping "). With (Girlfriend :: AddHobby, "Shopping "). "Shopping "). With (GirlFriend::addGift, "LBR 1912 queen "). With (GirlFriend::addGift," birthday present ", "Dior Flame Blue and Gold ").with(Girlfriend ::addGift," anniversary gift ", "Armani Red tube lip glaze ") // blah blah blah... .build(); }}
See! Instantiation and property set in the same statement, chain operation, all the way dot dot, cool!
Talk is cheap, show me the code
/** * Generic Builder pattern Builder ** @Author: CipherCui * @since 2019/8/29 */ public class Builder<T> { private final Supplier<T> instantiator; private List<Consumer<T>> modifiers = new ArrayList<>(); public Builder(Supplier<T> instantiator) { this.instantiator = instantiator; } public static <T> Builder<T> of(Supplier<T> instantiator) { return new Builder<>(instantiator); } public <P1> Builder<T> with(Consumer1<T, P1> consumer, P1 p1) { Consumer<T> c = instance -> consumer.accept(instance, p1); modifiers.add(c); return this; } public <P1, P2> Builder<T> with(Consumer2<T, P1, P2> consumer, P1 p1, P2 p2) { Consumer<T> c = instance -> consumer.accept(instance, p1, p2); modifiers.add(c); return this; } public <P1, P2, P3> Builder<T> with(Consumer3<T, P1, P2, P3> consumer, P1 p1, P2 p2, P3 p3) { Consumer<T> c = instance -> consumer.accept(instance, p1, p2, p3); modifiers.add(c); return this; } public T build() { T value = instantiator.get(); modifiers.forEach(modifier -> modifier.accept(value)); modifiers.clear(); return value; } /** * 1 Consumer */ @FunctionalInterface public interface Consumer1<T, P1> {void accept(T T, P1 P1); } / Consumer * / * * * 2 parameter @ FunctionalInterface public interface Consumer2 < T, P1, P2 > {void the accept (T, T, P1 P1, P2 P2); } / Consumer * / * * * 3 parameter @ FunctionalInterface public interface Consumer3 < T, P1, P2, P3 > {void the accept (T, T, P1 P1, P2 p2, P3 p3); }}
This example supports a set property method with up to three parameters, which is quite sufficient. If you want to extend it, it’s easy to follow suit and add a Consumer with multiple parameters.
Use your Builder to create an object
Recommended reading
IDEA2020.2.3 hack, IDEA2020.2 activation hack, IDEA activation code
Amazing, this Java website, everything! https://markerhub.com
The B station of the UP Lord, the JAVA is really good!
SpringBoot+Vue Front and Back End Separation complete tutorial!
Too great! The latest edition of Java programming ideas can be viewed online!
The latest frequently asked business interview questions of 2021 and their answers