// 생성자
public Boolean(boolean value) {
this.value = value;
}
클래스의 인스턴스를 반환하는 단순한 static 메서드
public static final Boolean TRUE = new Boolean(true);
public static final Boolean FALSE = new Boolean(false);
// 정적 팩터리 메서드
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}
위 예시의 valueOf함수와 같이 다양한 이름을 설정 가능
new BigInteger(int, int, Random);
BigInteger.probablePrime;
// 이쪽이 소수인 BigInteger를 반환한다 라는 의미를 더 잘 전달
싱글턴 패턴 구현가능
인스턴스화 불가
등 인스턴스가 단 하나임을 보장할 수 있도록 할 수 있음
public class LottoNumber {
private static final int MIN_LOTTO_NUMBER = 1;
private static final int MAX_LOTTO_NUMBER = 45;
private static Map<Integer, LottoNumber> lottoNumberCache = new HashMap<>();
static {
IntStream.range(MIN_LOTTO_NUMBER, MAX_LOTTO_NUMBER)
.forEach(i -> lottoNumberCache.put(i, new LottoNumber(i)));
}
private int number;
// 생성자로 직접 인스턴스화 하지 못하도록 함
private LottoNumber(int number) {
this.number = number;
}
public LottoNumber of(int number) { // LottoNumber를 반환하는 정적 팩토리 메서드
return lottoNumberCache.get(number);
}
...
}
// 출처 : https://tecoble.techcourse.co.kr/post/2020-05-26-static-factory-method/
class Hero {
public static Hero of(String job){
if (job == "전사") {
return new Warrior();
} else if (job == "마법사") {
return new Wizard();
} else {
return new Archer();
}
}
}
// 원소의 수에 따라 두 가지 하위 클래스 중 하나를 반환하는 EnumSet
if (universe.length <= 64)
return new RegularEnumSet<>(elementType, universe);
else
return new JumboEnumSet<>(elementType, universe);