PHP · 패턴
Factory Method
타입 문자열에 따라 적절한 구현체를 생성하는 factory 패턴 예제입니다.
패턴중급factorynotifiercreation
핵심 설명
타입 문자열에 따라 적절한 구현체를 생성하는 factory 패턴 예제입니다.
PHP code
<?php
interface Notifier {
public function send(string $message): string;
}
class EmailNotifier implements Notifier {
public function send(string $message): string { return 'mail:' . $message; }
}
class NotifierFactory {
public static function make(string $type): Notifier {
return match ($type) {
'email' => new EmailNotifier(),
default => throw new InvalidArgumentException('unsupported'),
};
}
}
echo NotifierFactory::make('email')->send('hi');학습 팁
패턴 예제는 클래스 수보다 의존성 방향과 책임 분리를 중심으로 읽는 것이 더 중요합니다.
주의할 점
패턴을 적용하더라도 구현체에 강하게 결합되면 오히려 변경 비용이 커집니다.
자주 묻는 질문
Factory Method란 무엇인가요?
타입 문자열에 따라 적절한 구현체를 생성하는 factory 패턴 예제입니다.
Factory Method 학습 시 주의할 점은 무엇인가요?
패턴을 적용하더라도 구현체에 강하게 결합되면 오히려 변경 비용이 커집니다.
Continue Learning
PHP 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.