Item 1. 생성자 대신 정적 팩터리 메서드를 고려하라
public class User {
private final String name;
private final String country;
public User(String name, String country) {
this.name = name;
this.country = country;
}
// standard getters / toString ...
}public class User {
private final String name;
private final String country;
private User(String name, String country) {
this.name = name;
this.country = country;
}
public static User createWithDefaultCountry(String name) {
return new User(name, "KOREA");
}
}Static Factory Method 장점
1. 이름을 가질 수 있다.
2. 호출이 될 때마다 새로운 인스턴스를 생성하지 않아도 된다.
3. 반환 타입의 하위 타입 객체를 반환할 수 있는 능력이 있다.
4. 입력 매개변수에 따라 매번 다른 클래스의 객체를 반환할 수 있다.
5. Static Factory Method를 작성하는 시점에는 반환할 객체의 클래스가 존재하지 않아도 된다.
Static Factory Method 단점
1. 상속은 public, protected 생성자가 필요하다.
2. 프로그래머가 찾기 어렵다.
Last updated