new
키워드 사용new
로 객체를 생성해 반환 => 내부에서 new
간접적 사용public class Person {
private final String name;
private final int position;
private Person(String name, int position) {
this.name = name;
this.position = position;
}
public static Person of(String name, int position) {
return new Person(name, position);
}
생성자에 넘기는 매개변수와 생성자 자체만으로는 반환될 객체의 특성을 제대로 설명하지 못한다.
반면 정적 팩터리 메소드는 이름만 잘 지으면 반환될 객체의 특성을 쉽게 묘사할 수 있다.
객체 생성시 생성 목적과 과정에 따라 생성자를 구별해서 사용할 필요가 있다.
해당 생성자의 내부 구조를 알고 있어야 목적에 맞게 객체를 생성할 수 있다.
반면에 정적 팩터리 메서드를 사용하면 메서드 네이밍에 따라 반환될 객체의 특성을 묘사 할 수가 있다.
=> 메서드 네이밍에 따라 코드의 가독성이 상승 할 수 있다.
기본 public 생성자
public class Person {
private final String name;
private final int position;
public Person(String name) {
this.name = name;
this.position = 0;
}
public Person(String name, int position) {
this.name = name;
this.position = position;
}
public static void main(String[] args) {
Person oing1 = new Person("oing");
Person oing2 = new Person("oing", 3);
}
}
public class Person {
private final String name;
private final int position;
private Person(String name, int position) {
this.name = name;
this.position = position;
}
public static Person createZeroPositionPerson(String name) {
return new Person(name, 0);
}
public static Person createPerson(String name, int position) {
return new Person(name, position);
}
public static void main(String[] args) {
Person oing1 = Person.createZeroPositionPerson("oing");
Person oing2 = Person.createPerson("oing", 3);
}
}
=> 어떠한 객체가 반환되는지 유추 가능
public final class Boolean implements java.io.Serializable,
Comparable<Boolean>
{
public static final Boolean TRUE = new Boolean(true);
public static final Boolean FALSE = new Boolean(false);
...
@HotSpotIntrinsicCandidate
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}
}
** 하위 타입 : 자식 클래스, 인터페이스의 구현체
class Fruit {
public static Fruit createApple() {
return new Apple();
}
public static Fruit createGrape() {
return new Grape();
}
}
반환 타입의 하위 타입이기만 하면 어떤 클래스의 객체를 반환하든 상관없다.
public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) {
Enum<?>[] universe = getUniverse(elementType);
if (universe == null)
throw new ClassCastException(elementType + " not an enum");
if (universe.length <= 64)
return new RegularEnumSet<>(elementType, universe);
else
return new JumboEnumSet<>(elementType, universe);
}
이펙티브 자바 - 아이템1 생성자 대신 정적 팩터리 메서드를 고려하라
https://tecoble.techcourse.co.kr/post/2020-05-26-static-factory-method/
우테코 레벨1의 두번째 미션의 '사다리 게임'에 처음으로 적용해봤다. 허브 코드에 신기한게 있길래 "이게 뭐에요??"하며 처음 접하게 되었다. 알고보니 이펙티브 자바의 첫번째 주제여서인지 다들 자주 사용하는 방식이었다.
말이 너무 어려워서 허브를 붙잡고 이것저것 물어봤더니 이제 좀 이해가 간다ㅎㅎㅎ
다시 한번 감사합니다 허브^^7 충성충성
좋은데요?