Java를 사용하는데 뭔가 그냥 쓰던데로만, 겉핥기 식으로만 알고 있던것들에 대해 다시 알아보려고 한다.
Builder Pattern으로 객체 생성을 알아보기 전 다른 객체 생성 방법에 대해 살짝 보고 가자!!
1. Java Beans Pattern
가장 익숙한 getter/setter를 이용하여 객체를 생성할때 필드를 주입하는 방식이다.
Person person = new Person();
person.setName("BackEnd developer");
person.setAge(30);
person.setAddress("BabREE");
아래에서 보겠지만 점층적 생성자 패턴과는 다르게 1회의 생성자 호출로 객체를 완전히 생성하지 못한다는 단점이 있다.
즉, setter 메소드를 통해 값이 계속 변할 수 있기 때문에 객체의 일관성(consistency)이 깨질 수 있다.
2. Telescoping Constructor Pattern(점층적 생성자 패턴)
각 생성자를 오버라이딩 해서 만드는 기초적인 방식이다.
장점은 쉽게 짤수 있다지만 단점이 명확하다.
생성자가 다른 생성자를 호출하는 방식으로, 코드 수정(필드 추가 등)이 필요한경우 수정이 굉장이 복잡하다
public class Person {
private final String name;
private final int age;
private final String email;
public Person(String name) {
this(name, 0);
}
public Person(String name, int age) {
this(name, age, null);
}
public Person(String name, int age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
}
추가로 가독성도 매우 떨어지는 단점이있다.
필드가 여러개일 경우 객체 생성시 필드를 한번에 입력해야되는데, 이때 알아보기가 힘들다...
SampleClass sampleClass = new SampleClass(10,"아야",0,0,1,"Y","code",1);
3. 빌더 패턴
내부에 Builder를 따로 만들어서 그 빌더를 통해 객체를 생성하는 패턴이다.
이 빌더패턴을 간단하게 바꿔서 setter에 return을 바꾸는 방법도 있지만 일단 기본 방법을 보려고한다.
public class Person {
private final String name;
private final int age;
private final String email;
public static class Builder {
private final String name; //not Null
private int age = 0;
private String email = "";
public Builder(String name) {
this.name = name;
}
public Builder age(int val) {
age = val;
return this;
}
public Builder email(String val) {
email= val;
return this;
}
public Person build() {
return new Person(this);
}
}
public Person(Builder builder) {
name = builder.name;
age = builder.age;
email = builder.email;
}
}
객체 생성
Person person = new Person().builder("BackEnd developer")
.age(30)
.email("jjwon@haha.com")
.build();
객체를 생성함과 동시에 필드값을 입력 해줘야되는 단점이있다.
성능적으로 중요하게 생각하는 코드라면 조심스래 사용하는것이 좋을것 같다.
추가++
빌더패턴을 조금더 간단하고 익숙하게 javaBean pattern을 수정해서 사용하는 방법이다.
public class Person {
private final String name;
private final int age;
private final String email;
public String getName(){
return name;
}
public Person setName(String name){
this.name = name;
return this;
}
public int getAge(){
return age;
}
public Person setAge(String age){
this.age = age;
return this;
}
public String getEmail(){
return email;
}
public Person setEmail(String email){
this.email = email;
return this;
}
}
Setter에서 값을 입력받고 Return this를 통해 객체 생성 할때 가독성을 늘려줄수 있다.
Person person = new Person().setAge(5).setName("BackEnd Developer").setEmail("jjwon@haha.com");
'Java > Basic' 카테고리의 다른 글
[Java/Basic] Daemon Thread란? 백그라운드 실행데몬? (0) | 2021.04.13 |
---|---|
[Java/Basic] Thread run과 start의 차이 (0) | 2021.04.12 |
[Java-Basic] 재귀함수를 통해 팩토리얼 연습 (0) | 2021.02.15 |
[Java-Basic] String, StringBuffer, StringBuilder 속도 비교 및 차이점 (0) | 2021.02.15 |
[Java] Collection 정리 Map이란 HashMap & TreeMap (0) | 2021.01.28 |