Programing/javascript

자바스크립트 Factory Pattern

Dongkkase 2025. 4. 19. 07:03
반응형

Factory Pattern(팩토리 패턴) 은 객체 생성 로직을 외부에 감추고, 동일한 인터페이스를 통해 객체를 생성할 수 있도록 도와주는 디자인 패턴입니다. 객체를 생성할 때 조건에 따라 다양한 객체를 반환할 수 있는 유연성이 큰 장점입니다.


🧱 Factory Pattern이란?

Factory Pattern은 객체 생성을 위한 인터페이스를 정의하고, 하위 클래스가 어떤 클래스를 인스턴스화할지를 결정하는 구조입니다. 자바스크립트에서는 보통 함수나 클래스를 사용하여 객체 생성을 추상화합니다.

function createUser(type, name) {
    if (type === 'admin') {
        return {
            name,
            role: 'Administrator',
            access() { return 'Full access granted'; }
        };
    } else if (type === 'guest') {
        return {
            name,
            role: 'Guest',
            access() { return 'Read-only access'; }
        };
    } else {
        return {
            name,
            role: 'User',
            access() { return 'Limited access'; }
        };
    }
}

const user1 = createUser('admin', 'Alice');
const user2 = createUser('guest', 'Bob');

✅ 장점

  1. 객체 생성 캡슐화: 복잡한 객체 생성 로직을 외부에 숨길 수 있음
  2. 유연성 증가: 조건에 따라 다양한 객체를 생성할 수 있음
  3. 코드 일관성 유지: 동일한 인터페이스를 제공함으로써 호출 방식이 통일됨

❌ 단점

  1. 디버깅 어려움: 내부적으로 어떤 객체가 생성되는지 추적이 어려울 수 있음
  2. 남용 우려: 단순한 객체에도 Factory를 남용하면 오히려 복잡도가 증가할 수 있음
  3. 상속이 필요한 경우 부적합: 클래스 상속 구조에는 적합하지 않음

🛠️ 실전 예시: Notification 팩토리

function createNotification(type, message) {
    const base = {
        message,
        send() {
            console.log(`Sending: ${this.message}`);
        }
    };

    if (type === 'email') {
        return Object.assign({}, base, {
            channel: 'Email',
            format() {
                return `Email >> ${this.message}`;
            }
        });
    }

    if (type === 'sms') {
        return Object.assign({}, base, {
            channel: 'SMS',
            format() {
                return `SMS >> ${this.message}`;
            }
        });
    }

    return Object.assign({}, base, {
        channel: 'Generic'
    });
}

const alert = createNotification('email', '서버 오류 발생');
console.log(alert.format()); // Email >> 서버 오류 발생
alert.send();

🧩 결론

Factory Pattern은 객체 생성에 유연성을 부여하고, 복잡한 조건 분기를 감추는 데 매우 효과적입니다. 단, 모든 객체 생성에 무조건 적용하기보다는 객체의 종류가 다양하거나 생성 방식이 복잡할 때 선택적으로 사용하는 것이 좋습니다.

반응형