클래스는 생성자와 별도로 정적 팩터리 메서드를 제공할 수 있다는 것을 염두해두고 필요한 경우 사용하자!
new 키워드로 생성자를 호출하려면 개발자는 매개변수와 내부 구조를 알고 있어야 함
BigInteger(int, int, Random)
vs BigInteger.probablePrime
정적 팩터리 메서드로 이름을 붙여주면 반환될 객체의 특성을 유추하기 쉬움
class Rectangle {
private int width;
private int height;
private Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public static Rectangle createSquare(int size) {
return new Rectangle(size, size);
}
public static Rectangle createRectangle(int width, int height) {
return new Rectangle(width, height);
}
}
메서드를 통해 간접적으로 객체를 생성하기 때문에, 객체 생성 및 통제 관리를 할 수 있게 됨
싱글톤 패턴
class Singleton {
private static Singleton instance;
private Singleton() {}
// 정적 팩토리 메서드
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Boolean 클래스
Boolean.valueOf(boolean)
→ 항상 동일한 Boolean.TRUE 나 Boolean.False 객체를 반환함 (캐싱된 객체 재사용)
interface SmarPhone {}
class Galaxy implements SmarPhone {}
class IPhone implements SmarPhone {}
class Huawei implements SmarPhone {}
class SmartPhones {
public static SmarPhone getSamsungPhone() {
return new Galaxy();
}
public static SmarPhone getApplePhone() {
return new IPhone();
}
public static SmarPhone getChinesePhone() {
return new Huawei();
}
}