-
아이템 1 생성자 대신 정적 팩터리 메서드를 고려하라
-
장점
-
장점 1 - 이름을 가질 수 있다
-
장점 2 - 호출될 때마다 인스턴스를 새로 생성하지 않아도 된다
-
장점 3- 반환 타입의 하위 타입 객체를 반환할 수 있는 능력이 있다
-
장점 4 - 입력 매개변수에 따라 매번 다른클래스의 객체를 반환할 수 있다
-
장점 5 - 정적 팩터리 메서드를 작성하는 시점에는 반환할 객체의 클래스가 존재하지 않아도 된다
-
단점
-
단점 1 - 상속을 하려면 public이나 protected 생성자가 필요하니 정적 팩터리 메서드만 제공하면 하위 클래스를 만들 수 없다
-
단점 2- 정적 팩터리 메서드는 프로그래머가 찾기 어렵다
-
정적 팩터리 메서드 명명 방식
-
핵심 정리
아이템 1 생성자 대신 정적 팩터리 메서드를 고려하라
정적 팩터리 메서드 = 객체의 생성을 담당하는 클래스 메서드
public class Car {
private String model;
// private 생성자
private Car(String model) {
this.model = model;
}
// 정적 팩터리 메서드
public static Car create(String model) {
return new Car(model);
}
public String getModel() {
return model;
}
}
public class Main {
public static void main(String[] args) {
Car car = Car.create("Tesla Model S");
System.out.println(car.getModel()); // Tesla Model S
}
}
장점
장점 1 - 이름을 가질 수 있다
생성자에 넘기는 매개변수와 생성자 자체만으로는 반환될 객체의 특성을 제대로 설명하지 못한다.
BigInteger(int, int, Random)과 정적 팩터리 메서드인 BigInteger.probablePrimeTime 을 비교해보면 정적 패터리 메서드가 “값이 소수인 BigInteger를 반환한다”라는 의미에 더 적합하다.
public class User {
private String name;
private int age;
private User(String name, int age) {
this.name = name;
this.age = age;
}
// 의미 있는 이름을 가진 정적 팩터리 메서드
public static User createWithAge(String name, int age) {
return new User(name, age);
}
public static User createWithoutAge(String name) {
return new User(name, 0); // 기본 나이 0
}
}
public class Main {
public static void main(String[] args) {
User user1 = User.createWithAge("Alice", 30);
User user2 = User.createWithoutAge("Bob");
System.out.println(user1.name); // Alice
System.out.println(user2.age); // 0
}
}
여기서 createWithAge와 createWithoutAge는 각 메서드의 목적을 분명하게 나타낸다.
장점 2 - 호출될 때마다 인스턴스를 새로 생성하지 않아도 된다
정적 팩터리 메서드는 매번 새로운 객체를 생성할 필요 없이 캐싱된 객체를 반환할 수 있다. 특히 불변 객체의 경우 자주 사용된다.
public class BooleanExample {
public static void main(String[] args) {
Boolean bool1 = Boolean.valueOf(true);
Boolean bool2 = Boolean.valueOf(true);
System.out.println(bool1 == bool2); // true
}
}
Boolean.valueOf()는 매번 새로운 객체를 생성하는 대신, true와 false에 대한 캐싱된 객체를 반환하므로 메모리 효율성이 높다.
장점 3- 반환 타입의 하위 타입 객체를 반환할 수 있는 능력이 있다
정적 팩터리 메서드는 반환 타입이 꼭 해당 클래스일 필요가 없고, 반환 타입의 하위 타입을 반환할 수 있다. 이를 통해 상속이나 인터페이스 구현에 유연성을 더할 수 있다.
interface Animal {
void sound();
}
class Dog implements Animal {
@Override
public void sound() {
System.out.println("Bark");
}
}
class Cat implements Animal {
@Override
public void sound() {
System.out.println("Meow");
}
}
public class AnimalFactory {
// 정적 팩터리 메서드로 하위 타입 반환
public static Animal createAnimal(String type) {
if (type.equalsIgnoreCase("dog")) {
return new Dog();
} else {
return new Cat();
}
}
}
public class Main {
public static void main(String[] args) {
Animal animal = AnimalFactory.createAnimal("dog");
animal.sound(); // Bark
}
}
AnimalFactory.createAnimal() 메서드는 Animal 타입을 반환하지만, 실제로는 하위 타입인 Dog 또는 Cat 객체를 반환할 수 있다.
장점 4 - 입력 매개변수에 따라 매번 다른클래스의 객체를 반환할 수 있다
반환 타입의 하위 타입이기만 하면 어떤 클래스의 객체를 반환하든 상관없다.심지어 다음 릴리스에서는 또 다른 클래스의 객체를 반환해도 된다.
interface Shape {
void draw();
}
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing Circle");
}
}
class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Drawing Rectangle");
}
}
public class ShapeFactory {
// 매개변수에 따라 다른 객체 반환
public static Shape createShape(String shapeType) {
if (shapeType.equalsIgnoreCase("circle")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("rectangle")) {
return new Rectangle();
} else {
throw new IllegalArgumentException("Unknown shape type");
}
}
}
public class Main {
public static void main(String[] args) {
Shape shape = ShapeFactory.createShape("circle");
shape.draw(); // Drawing Circle
}
}
여기서 ShapeFactory.createShape()는 매개변수에 따라 Circle이나 Rectangle 객체를 반환한다.
장점 5 - 정적 팩터리 메서드를 작성하는 시점에는 반환할 객체의 클래스가 존재하지 않아도 된다
정적 팩터리 메서드는 인터페이스나 추상 클래스 같은 상위 타입을 반환할 수 있다. 이를 통해 나중에 그 인터페이스나 추상 클래스를 구현한 구체적인 클래스들이 정의될 때, 해당 클래스들을 반환할 수 있는 구조를 만들 수 있다.
- 기본 구조
먼저, 결제 처리를 위한 Payment 인터페이스를 정의하자. 구체적인 결제 방식 클래스들은 추후 추가될 수 있지만, 현재는 CreditCardPayment와 PayPalPayment만 구현되어 있다고 가정한다.
// Payment 인터페이스
public interface Payment {
void process();
}
// CreditCardPayment 클래스
public class CreditCardPayment implements Payment {
@Override
public void process() {
System.out.println("Processing Credit Card Payment");
}
}
// PayPalPayment 클래스
public class PayPalPayment implements Payment {
@Override
public void process() {
System.out.println("Processing PayPal Payment");
}
}
- 정적 팩터리 메서드 작성
PaymentFactory라는 클래스에서 정적 팩터리 메서드를 작성한다. 이 메서드는 Payment 인터페이스 타입을 반환하므로, 현재는 존재하지 않는 새로운 결제 방식을 추가하더라도 기존 팩터리 메서드를 수정하지 않아도 된다.
public class PaymentFactory {
// 정적 팩터리 메서드
public static Payment createPayment(String type) {
if (type.equalsIgnoreCase("creditcard")) {
return new CreditCardPayment();
} else if (type.equalsIgnoreCase("paypal")) {
return new PayPalPayment();
} else {
throw new IllegalArgumentException("Unknown payment type");
}
}
3. 추후에 추가될 결제 방식
현재는 CreditCardPayment와 PayPalPayment만 구현되어 있지만, 추후에 새로운 결제 방식, 예를 들어 Bitcoin 결제가 추가될 수도 있다. 이때 새로운 BitcoinPayment 클래스를 추가하고 팩터리 메서드에서 반환할 수 있도록 하면 된다.
// BitcoinPayment 클래스
public class BitcoinPayment implements Payment {
@Override
public void process() {
System.out.println("Processing Bitcoin Payment");
}
}
그 후, 팩터리 메서드에서 이 새로운 결제 방식을 처리하도록 로직을 추가한다.
public class PaymentFactory {
public static Payment createPayment(String type) {
if (type.equalsIgnoreCase("creditcard")) {
return new CreditCardPayment();
} else if (type.equalsIgnoreCase("paypal")) {
return new PayPalPayment();
} else if (type.equalsIgnoreCase("bitcoin")) {
return new BitcoinPayment(); // 새로운 결제 방식 추가
} else {
throw new IllegalArgumentException("Unknown payment type");
}
}
}
4. 구체적인 클래스가 존재하지 않아도 되는 이유
이 시점에서 중요한 점은, 정적 팩터리 메서드를 작성하는 시점에서는 BitcoinPayment 클래스가 존재하지 않았지만, 이 메서드는 여전히 잘 작동한다는 점이다. 이유는 PaymentFactory가 반환하는 것은 상위 타입인 Payment 인터페이스이기 때문.
즉, 처음에 정적 팩터리 메서드를 설계할 때는 구체적인 하위 클래스들이 모두 정의되어 있을 필요가 없다. 추후에 새로운 하위 클래스를 추가하기만 하면 정적 팩터리 메서드는 문제없이 그 새로운 클래스 객체를 반환할 수 있다.
5. 실제 사용
public class Main {
public static void main(String[] args) {
Payment payment = PaymentFactory.createPayment("bitcoin");
payment.process(); // Processing Bitcoin Payment
}
}
PaymentFactory.createPayment("bitcoin")을 호출하면 이제 BitcoinPayment 객체가 반환되고, 새로운 결제 방식이 자연스럽게 추가된 것.
단점
단점 1 - 상속을 하려면 public이나 protected 생성자가 필요하니 정적 팩터리 메서드만 제공하면 하위 클래스를 만들 수 없다
A클래스의 생성자를 private으로 막아두면 extends A 와 같은 형태로 사용할 수 없다.
단점 2- 정적 팩터리 메서드는 프로그래머가 찾기 어렵다
정적 팩터리 메서드는 개발자가 직접 만들어주는 함수이기 때문에 비교적 생성자보다 찾기 어렵다고 할 수 있다.
그래서 메서드 이름도 널리 알려진 규약을 따라 짓는 식으로 문제를 완화해줘야 한다.
정적 팩터리 메서드 명명 방식
from
매개변수를 하나 받아서 해당 타입의 인스턴스를 반환하는 형변환 메서드
Date d = Date.from(instant);
of
여러 매개변수를 받아 적합한 타입의 인스턴스를 반환하는 집계 메서드
LocalDate.of(2023, 2, 5)
valueOf
from과 of의 더 자세한 버전
String.valueOf(10);
instance, getInstance
(매개변수를 받는다면) 매개변수로 명시한 인스턴스를 반환하지만, 같은 인스턴스임을 보장하지는 않는다. (싱글턴 구현에서 주로 getInstance() 를 많이 사용한다.)
StackWalker luke = StackWalker.getInstance(options);
create, newInstance
instance 혹은 getInstance와 같지만, 매번 새로운 인스턴스를 생성해 반환함을 보장한다.
Array.newInstance(classObject, arrayLen);
getType
getInstance와 같으나, 생성할 클래스가 아닌 다른 클래스에 팩터리 메서드를 정의할 때 쓴다. "Type"은 팩터리 메서드가 반환할 객체의 타입이다.
BufferedReader br = Files.newBufferedReader(path);
type
getType과 newType의 간결한 버전
List<Complaint> litany = Collections.list(legacyLitany);
핵심 정리
정적 팩터리 메서드와 public 생성자는 각자의 쓰임새가 있으니 상대적인 장단점을 이해하고 사용하는 것이 좋다. 그렇다고 하더라도 정적 팩터리를 사용하는 게 유리한 경우가 더 많으므로 무작정 public 생성자를제공하던 습관이 있다면 고치자.
'Java' 카테고리의 다른 글
이펙티브 자바(Effective Java) 2장 - 아이템 6 불필요한 객체 생성을 피하라 (0) | 2024.12.03 |
---|---|
이펙티브 자바(Effective Java) 2장 - 아이템 5 자원을 직접 명시하지 말고 의존 객체 주입을 사용하라 (0) | 2024.12.03 |
이펙티브 자바(Effective Java) 2장 - 아이템 4 인스턴스화를 막으려거든 private 생성자를 사용하라 (0) | 2024.12.03 |
이펙티브 자바(Effective Java) 2장 - 아이템 3 private 생성자나 열거 타입으로 싱글턴임을 보증하라 (0) | 2024.12.03 |
이펙티브 자바(Effective Java) 2장 - 아이템 2 생성자에 매개변수가 많다면 빌더를 고려하라 (0) | 2024.12.03 |
아이템 1 생성자 대신 정적 팩터리 메서드를 고려하라
정적 팩터리 메서드 = 객체의 생성을 담당하는 클래스 메서드
public class Car { private String model; // private 생성자 private Car(String model) { this.model = model; } // 정적 팩터리 메서드 public static Car create(String model) { return new Car(model); } public String getModel() { return model; } } public class Main { public static void main(String[] args) { Car car = Car.create("Tesla Model S"); System.out.println(car.getModel()); // Tesla Model S } }
장점
장점 1 - 이름을 가질 수 있다
생성자에 넘기는 매개변수와 생성자 자체만으로는 반환될 객체의 특성을 제대로 설명하지 못한다.
BigInteger(int, int, Random)과 정적 팩터리 메서드인 BigInteger.probablePrimeTime 을 비교해보면 정적 패터리 메서드가 “값이 소수인 BigInteger를 반환한다”라는 의미에 더 적합하다.
public class User { private String name; private int age; private User(String name, int age) { this.name = name; this.age = age; } // 의미 있는 이름을 가진 정적 팩터리 메서드 public static User createWithAge(String name, int age) { return new User(name, age); } public static User createWithoutAge(String name) { return new User(name, 0); // 기본 나이 0 } } public class Main { public static void main(String[] args) { User user1 = User.createWithAge("Alice", 30); User user2 = User.createWithoutAge("Bob"); System.out.println(user1.name); // Alice System.out.println(user2.age); // 0 } }
여기서 createWithAge와 createWithoutAge는 각 메서드의 목적을 분명하게 나타낸다.
장점 2 - 호출될 때마다 인스턴스를 새로 생성하지 않아도 된다
정적 팩터리 메서드는 매번 새로운 객체를 생성할 필요 없이 캐싱된 객체를 반환할 수 있다. 특히 불변 객체의 경우 자주 사용된다.
public class BooleanExample { public static void main(String[] args) { Boolean bool1 = Boolean.valueOf(true); Boolean bool2 = Boolean.valueOf(true); System.out.println(bool1 == bool2); // true } }
Boolean.valueOf()는 매번 새로운 객체를 생성하는 대신, true와 false에 대한 캐싱된 객체를 반환하므로 메모리 효율성이 높다.
장점 3- 반환 타입의 하위 타입 객체를 반환할 수 있는 능력이 있다
정적 팩터리 메서드는 반환 타입이 꼭 해당 클래스일 필요가 없고, 반환 타입의 하위 타입을 반환할 수 있다. 이를 통해 상속이나 인터페이스 구현에 유연성을 더할 수 있다.
interface Animal { void sound(); } class Dog implements Animal { @Override public void sound() { System.out.println("Bark"); } } class Cat implements Animal { @Override public void sound() { System.out.println("Meow"); } } public class AnimalFactory { // 정적 팩터리 메서드로 하위 타입 반환 public static Animal createAnimal(String type) { if (type.equalsIgnoreCase("dog")) { return new Dog(); } else { return new Cat(); } } } public class Main { public static void main(String[] args) { Animal animal = AnimalFactory.createAnimal("dog"); animal.sound(); // Bark } }
AnimalFactory.createAnimal() 메서드는 Animal 타입을 반환하지만, 실제로는 하위 타입인 Dog 또는 Cat 객체를 반환할 수 있다.
장점 4 - 입력 매개변수에 따라 매번 다른클래스의 객체를 반환할 수 있다
반환 타입의 하위 타입이기만 하면 어떤 클래스의 객체를 반환하든 상관없다.심지어 다음 릴리스에서는 또 다른 클래스의 객체를 반환해도 된다.
interface Shape { void draw(); } class Circle implements Shape { @Override public void draw() { System.out.println("Drawing Circle"); } } class Rectangle implements Shape { @Override public void draw() { System.out.println("Drawing Rectangle"); } } public class ShapeFactory { // 매개변수에 따라 다른 객체 반환 public static Shape createShape(String shapeType) { if (shapeType.equalsIgnoreCase("circle")) { return new Circle(); } else if (shapeType.equalsIgnoreCase("rectangle")) { return new Rectangle(); } else { throw new IllegalArgumentException("Unknown shape type"); } } } public class Main { public static void main(String[] args) { Shape shape = ShapeFactory.createShape("circle"); shape.draw(); // Drawing Circle } }
여기서 ShapeFactory.createShape()는 매개변수에 따라 Circle이나 Rectangle 객체를 반환한다.
장점 5 - 정적 팩터리 메서드를 작성하는 시점에는 반환할 객체의 클래스가 존재하지 않아도 된다
정적 팩터리 메서드는 인터페이스나 추상 클래스 같은 상위 타입을 반환할 수 있다. 이를 통해 나중에 그 인터페이스나 추상 클래스를 구현한 구체적인 클래스들이 정의될 때, 해당 클래스들을 반환할 수 있는 구조를 만들 수 있다.
- 기본 구조
먼저, 결제 처리를 위한 Payment 인터페이스를 정의하자. 구체적인 결제 방식 클래스들은 추후 추가될 수 있지만, 현재는 CreditCardPayment와 PayPalPayment만 구현되어 있다고 가정한다.
// Payment 인터페이스 public interface Payment { void process(); } // CreditCardPayment 클래스 public class CreditCardPayment implements Payment { @Override public void process() { System.out.println("Processing Credit Card Payment"); } } // PayPalPayment 클래스 public class PayPalPayment implements Payment { @Override public void process() { System.out.println("Processing PayPal Payment"); } }
- 정적 팩터리 메서드 작성
PaymentFactory라는 클래스에서 정적 팩터리 메서드를 작성한다. 이 메서드는 Payment 인터페이스 타입을 반환하므로, 현재는 존재하지 않는 새로운 결제 방식을 추가하더라도 기존 팩터리 메서드를 수정하지 않아도 된다.
public class PaymentFactory { // 정적 팩터리 메서드 public static Payment createPayment(String type) { if (type.equalsIgnoreCase("creditcard")) { return new CreditCardPayment(); } else if (type.equalsIgnoreCase("paypal")) { return new PayPalPayment(); } else { throw new IllegalArgumentException("Unknown payment type"); } }
3. 추후에 추가될 결제 방식
현재는 CreditCardPayment와 PayPalPayment만 구현되어 있지만, 추후에 새로운 결제 방식, 예를 들어 Bitcoin 결제가 추가될 수도 있다. 이때 새로운 BitcoinPayment 클래스를 추가하고 팩터리 메서드에서 반환할 수 있도록 하면 된다.
// BitcoinPayment 클래스 public class BitcoinPayment implements Payment { @Override public void process() { System.out.println("Processing Bitcoin Payment"); } }
그 후, 팩터리 메서드에서 이 새로운 결제 방식을 처리하도록 로직을 추가한다.
public class PaymentFactory { public static Payment createPayment(String type) { if (type.equalsIgnoreCase("creditcard")) { return new CreditCardPayment(); } else if (type.equalsIgnoreCase("paypal")) { return new PayPalPayment(); } else if (type.equalsIgnoreCase("bitcoin")) { return new BitcoinPayment(); // 새로운 결제 방식 추가 } else { throw new IllegalArgumentException("Unknown payment type"); } } }
4. 구체적인 클래스가 존재하지 않아도 되는 이유
이 시점에서 중요한 점은, 정적 팩터리 메서드를 작성하는 시점에서는 BitcoinPayment 클래스가 존재하지 않았지만, 이 메서드는 여전히 잘 작동한다는 점이다. 이유는 PaymentFactory가 반환하는 것은 상위 타입인 Payment 인터페이스이기 때문.
즉, 처음에 정적 팩터리 메서드를 설계할 때는 구체적인 하위 클래스들이 모두 정의되어 있을 필요가 없다. 추후에 새로운 하위 클래스를 추가하기만 하면 정적 팩터리 메서드는 문제없이 그 새로운 클래스 객체를 반환할 수 있다.
5. 실제 사용
public class Main { public static void main(String[] args) { Payment payment = PaymentFactory.createPayment("bitcoin"); payment.process(); // Processing Bitcoin Payment } }
PaymentFactory.createPayment("bitcoin")을 호출하면 이제 BitcoinPayment 객체가 반환되고, 새로운 결제 방식이 자연스럽게 추가된 것.
단점
단점 1 - 상속을 하려면 public이나 protected 생성자가 필요하니 정적 팩터리 메서드만 제공하면 하위 클래스를 만들 수 없다
A클래스의 생성자를 private으로 막아두면 extends A 와 같은 형태로 사용할 수 없다.
단점 2- 정적 팩터리 메서드는 프로그래머가 찾기 어렵다
정적 팩터리 메서드는 개발자가 직접 만들어주는 함수이기 때문에 비교적 생성자보다 찾기 어렵다고 할 수 있다.
그래서 메서드 이름도 널리 알려진 규약을 따라 짓는 식으로 문제를 완화해줘야 한다.
정적 팩터리 메서드 명명 방식
from
매개변수를 하나 받아서 해당 타입의 인스턴스를 반환하는 형변환 메서드
Date d = Date.from(instant);
of
여러 매개변수를 받아 적합한 타입의 인스턴스를 반환하는 집계 메서드
LocalDate.of(2023, 2, 5)
valueOf
from과 of의 더 자세한 버전
String.valueOf(10);
instance, getInstance
(매개변수를 받는다면) 매개변수로 명시한 인스턴스를 반환하지만, 같은 인스턴스임을 보장하지는 않는다. (싱글턴 구현에서 주로 getInstance() 를 많이 사용한다.)
StackWalker luke = StackWalker.getInstance(options);
create, newInstance
instance 혹은 getInstance와 같지만, 매번 새로운 인스턴스를 생성해 반환함을 보장한다.
Array.newInstance(classObject, arrayLen);
getType
getInstance와 같으나, 생성할 클래스가 아닌 다른 클래스에 팩터리 메서드를 정의할 때 쓴다. "Type"은 팩터리 메서드가 반환할 객체의 타입이다.
BufferedReader br = Files.newBufferedReader(path);
type
getType과 newType의 간결한 버전
List<Complaint> litany = Collections.list(legacyLitany);
핵심 정리
정적 팩터리 메서드와 public 생성자는 각자의 쓰임새가 있으니 상대적인 장단점을 이해하고 사용하는 것이 좋다. 그렇다고 하더라도 정적 팩터리를 사용하는 게 유리한 경우가 더 많으므로 무작정 public 생성자를제공하던 습관이 있다면 고치자.
'Java' 카테고리의 다른 글
이펙티브 자바(Effective Java) 2장 - 아이템 6 불필요한 객체 생성을 피하라 (0) | 2024.12.03 |
---|---|
이펙티브 자바(Effective Java) 2장 - 아이템 5 자원을 직접 명시하지 말고 의존 객체 주입을 사용하라 (0) | 2024.12.03 |
이펙티브 자바(Effective Java) 2장 - 아이템 4 인스턴스화를 막으려거든 private 생성자를 사용하라 (0) | 2024.12.03 |
이펙티브 자바(Effective Java) 2장 - 아이템 3 private 생성자나 열거 타입으로 싱글턴임을 보증하라 (0) | 2024.12.03 |
이펙티브 자바(Effective Java) 2장 - 아이템 2 생성자에 매개변수가 많다면 빌더를 고려하라 (0) | 2024.12.03 |