layout | title | catalog | date | subtitle | header-img | tags | ||
---|---|---|---|---|---|---|---|---|
post |
μΈν
리μ μ΄λ‘ Builder Pattern μ½κ² ꡬννκΈ° |
true |
2018-01-17 17:25:21 -0800 |
|
μ΄λ―Έ λ§μ λΆλ€μ΄ λΉλ ν¨ν΄ κ΄λ ¨ν΄μ ν¬μ€ν μ μ μ 리ν΄μ£Όμ μ λΉλ ν¨ν΄μ λν΄μ μ€λͺ ν΄μ£ΌκΈ° 보λ€λ μΈν 리μ μ΄ νλ¬κ·ΈμΈμ νμ©ν΄μ μ’ μ½κ² μ¬μ©ν μ μλ νμ ν¬μ€ν μ ν΄λ³΄κ² μ΅λλ€. λ¬Όλ‘ Lombokμ νμ©ν΄μ λΉλλ₯Ό μμ½κ² μ¬μ©ν μμμ§λ§ Lombokμ μ¬μ©νμ§ μκ³ λ μ½κ² λ§λ€ μ μλ λ°©λ²μ μκ°ν΄λλ¦¬κ² μ΅λλ€.
Preferences -> Plugins -> Browse Repositories -> Builder Generator κ²μ λ° μ€μΉ
command + n
ν€λ₯Ό λλ¬ Builder λ₯Ό μ νν©λλ€.- μ νλ©΄μ²λΌ Builder ν΄λμ€λ₯Ό μμ±ν©λλ€.
public class Member {
private String name; //mandatory
private String email; //mandatory
private String mobile; //optional
private String address; //optional
private String password; //optional
private String state; //optional
private int age; //optional
//Getter, Setter, Constructor
}
Member member = new Member(name, email, mobile ....)
- κ°μ²΄λ₯Ό μμ±ν λ μ΄λ€ κ°μ΄ νμ κ°μΈμ§ μ΅μ κ°μΈμ§ μΈμ§ νκΈ° μ΄λ ΅λ€.
Member member = new Member(name, email, mobile ....)
μμ±μλ‘ κ°μ²΄λ₯Ό μμ± ν κ²½μ° λ°λμ μμλ₯Ό λ§μΆμΌ νλ€.Setter
λ‘ μμ±ν κ²½μ° Setter λ©μλλ₯Ό λ§μ΄ μμ±ν΄μΌνλ€.
- λΉλ ν¨ν΄μ μ¬μ©ν΄μ νμ κ°μ μμ±μλ‘ μ΅μ κ°μ λΉλ ν΄λμ€λ‘ μμ±νλ€.
public final class MemberBuilder {
private final String name; //mandatory
private final String email; //mandatory
private String mobile; //optional
private String address; //optional
private String password; //optional
private String state; //optional
private int age; //optional
private MemberBuilder(String name, String email) {
this.name = name;
this.email = email;
}
public static MemberBuilder aMember(String name, String email) {
return new MemberBuilder(name, email);
}
public MemberBuilder withMobile(String mobile) {
this.mobile = mobile;
return this;
}
public MemberBuilder withAddress(String address) {
this.address = address;
return this;
}
public MemberBuilder withPassword(String password) {
this.password = password;
return this;
}
public MemberBuilder withState(String state) {
this.state = state;
return this;
}
public MemberBuilder withAge(int age) {
this.age = age;
return this;
}
public Member build() {
Member member = new Member();
member.setName(name);
member.setEmail(email);
member.setMobile(mobile);
member.setAddress(address);
member.setPassword(password);
member.setState(state);
member.setAge(age);
return member;
}
}
- νμ λ§΄λ² νλμΈ
name, email
μfinal
μ μΆκ°ν©λλ€. - μμ±μ νλΌλ―Έν°μ
name, email
μΆκ°ν©λλ€. - μλμΌλ‘ λ§λ€μ΄μ€
name, email
μwith
λ©μλλ₯Ό μ κ±° ν©λλ€.
Member member = MemberBuilder
.aMember("Yun", "[email protected]")
.withAddress("address")
.withAge(20)
.withMobile("010-XXXX-XXXX")
.build();
- νμ κ°μ μμ±μλ‘ λ겨 νμ κ°μ λ겨 νμ κ°μ μΈμ§ νκΈ° μ½μ΅λλ€.
- μ΅μ
κ°λ€μ μμμ μκ΄ μμ΄ .
with...()
λ©μλλ‘ μ΄μ΄λκ°λλ€.
κ°μ²΄λ₯Ό μμ νκ² μμ±νκ³ μ½κ² μμ±ν μ μλ€λ μ₯μ μ΄ μμ΅λλ€. κ°λ λ κ·Έλ κ² μ΄λ ΅μ§ μμ κ°μ₯ λ§λ§νκ² λμ ν΄ λ³Όλ§ν λμμΈ ν¨ν΄μΈκ±° κ°μ΅λλ€.