본문 바로가기
개발/JAVA

[JAVA] 정적 팩토리 메소드란? (static factory method)

by zuzuu 2022. 1. 10.
반응형

 

정적 팩토리 메서드

정적(static), 팩토리(factory), 메서드(method)

GoF라는 디자인 패턴 중 팩토리 패턴에서 유래한 단어로 객체를 생성하는 역할을 분리하겠다는 것을 말한다.

(하지만 정적 팩토리 메서드와 팩토리 패턴은 명확하게 다르고, 디자인 패턴 중에 이와 일치하는 패턴이 없다고 한다. 이 부분에 대해선 공부를 해봐야겠다..)

좀 더 쉽게 설명하자면 생성자를 통해 객체를 생성하는게 아니라 별도 메소드를 정의해서 객체를 생성할 수 있도록 객체 내에 정적 메소드를 정의해놓은 것!


정확히 어떤 메소드를 얘기하는 건지 예시를 들어보겠다.

java.time 패키지에 포함된 LocalDateTime 클래스의 정적 팩토리 메서드를 살펴 보면 생성자를 통해 객체를 생성하는 것이 아니라 of 메소드를 사용하고, of 메소드 내부에 객체를 생성하는 코드가 있는 것을 볼 수 있다.

LocalDateTime ldt = LocalDateTime.of(2022, 1, 1, 1, 30, 0);
public static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second) {
        LocalDate date = LocalDate.of(year, month, dayOfMonth);
        LocalTime time = LocalTime.of(hour, minute, second);
        return new LocalDateTime(date, time);
}

 

 

그리고 java.math 패키지에 포함된 BigInteger클래스의 경우도 valueOf, smallPrime, largePrime 등의 메소드를 제공하는데 해당 메소드를 살펴보면 메소드 내부에서 객체를 생성하고 있다.

public static BigInteger valueOf(long val) {
        // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant
        if (val == 0)
            return ZERO;
        if (val > 0 && val <= MAX_CONSTANT)
            return posConst[(int) val];
        else if (val < 0 && val >= -MAX_CONSTANT)
            return negConst[(int) -val];

        return new BigInteger(val);
}

 

private static BigInteger smallPrime(int bitLength, int certainty, Random rnd) {
        int magLen = (bitLength + 31) >>> 5;
        int temp[] = new int[magLen];
        int highBit = 1 << ((bitLength+31) & 0x1f);  // High bit of high int
        int highMask = (highBit << 1) - 1;  // Bits to keep in high int

        while (true) {
            // Construct a candidate
            for (int i=0; i < magLen; i++)
                temp[i] = rnd.nextInt();
            temp[0] = (temp[0] & highMask) | highBit;  // Ensure exact length
            if (bitLength > 2)
                temp[magLen-1] |= 1;  // Make odd if bitlen > 2

            BigInteger p = new BigInteger(temp, 1);

            // Do cheap "pre-test" if applicable
            if (bitLength > 6) {
                long r = p.remainder(SMALL_PRIME_PRODUCT).longValue();
                if ((r%3==0)  || (r%5==0)  || (r%7==0)  || (r%11==0) ||
                    (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
                    (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0))
                    continue; // Candidate is composite; try another
            }

            // All candidates of bitLength 2 and 3 are prime by this point
            if (bitLength < 4)
                return p;

            // Do expensive test if we survive pre-test (or it's inapplicable)
            if (p.primeToCertainty(certainty, rnd))
                return p;
        }
    }

 

이렇게 정적 팩토리 메서드가 무엇인지 알게 되면 생성자가 있는데 왜 정적 팩토리 메서드를 사용해야 하는 건지 의문이 생긴다!  '생성자 대신 정적 팩토리 메서드를 고려하라'라는 말도 있고..

생성자와 어떤 차이가 있고, 정적 팩토리 메서드의 장점이 무엇인지는 다음 포스팅에서~!

 

위 내용 포스팅 작성 완료!

 

[JAVA] 생성자 대신 정적 팩토리 메소드를 고려해야 하는 이유!

먼저 정적 팩토리 메소드가 뭔지 잘 모르겠으면 아래 포스팅을 보고 오자! [Java] 정적 팩토리 메소드란? (static factory method) 정적 팩토리 메서드 정적(static), 팩토리(factory), 메서드(method) GoF라는 디.

ynzu-dev.tistory.com

 

728x90
반응형

댓글