정적 팩토리 메서드(Static Factory Method) 는 무엇이며 왜 사용할까?
private String model;
!!! private Car(String model) {
this.model = model;
}
보통 생성자는 3라인의 생성자를 통해 만들어 왔다.
하지만 생성자는 메서드 명이 없기때문에 어떤 객체가 변경되는지, 어떤 행위를 표현하는지 이해하기 힘들다.
정적 팩토리 메서드는 이 부분을 생성자가 아닌 정적 메서드를 통해 객체를 생성하는 방법이다.
이를 통해 얻을 수 있는 이점은
또한 중간에 static 메서드가 들어가는 이유는 메모리적인 측면에서 유리하기 때문이다.
위의 코드를 정적 팩토리 메서드를 사용한다면
public static Car createElectricCar() {
return new Car("Electric Car");
}
public static Car createPetrolCar() {
return new Car("Petrol Car");
}
이런 식으로 정적 팩토리 메서드를 사용할 수 있다.
정적 팩토리 메서드 사용 예시
@Transactional
public StoreEditResponseDto updateStore(Long id, StoreEditRequsetDto storeEditRequsetDto) {
Store store = storeRepository.findById(id).orElseThrow(IllegalArgumentException::new);
store.update(storeEditRequsetDto);
return StoreEditResponseDto.from(store);
}
public class StoreEditResponseDto {
private String name;
private String description;
private String category;
private String address;
private String phoneNumber;
private String status;
public static StoreEditResponseDto from(Store store) {
StoreEditResponseDto dto = new StoreEditResponseDto();
dto.name = store.getName();
dto.description = store.getDescription();
dto.category = store.getCategory();
dto.address = store.getAddress();
dto.phoneNumber = store.getPhoneNumber();
dto.status = store.getStatus();
return dto;
}
}
위와 같이
1. 생성자에 여러 매개변수를 전달해야 할 때
2. 객체의 불변성/상태 관리
3. 객체 생성 과정이 복잡할 때
4. 다형성 활용
5. 싱글톤 패턴
등의 시점에서 사용된다.
정적 팩토리 메서드 네이밍 컨벤션
from : 하나의 매개 변수를 받아서 객체를 생성
of : 여러개의 매개 변수를 받아서 객체를 생성
getInstance | instance : 인스턴스를 생성. 이전에 반환했던 것과 같을 수 있음.
newInstance | create : 새로운 인스턴스를 생성
get[OtherType] : 다른 타입의 인스턴스를 생성. 이전에 반환했던 것과 같을 수 있음.
new[OtherType] : 다른 타입의 새로운 인스턴스를 생성.