팩토리 패턴
Coddy PHP 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 91개 중 72번째.
Factory 패턴은 객체 생성을 별도의 클래스나 method에 위임하는 생성 디자인 패턴입니다. 코드 전체에서 new를 직접 사용하는 대신, factory에 객체를 생성해 달라고 요청합니다.
이 패턴은 공통 interface를 공유하는 여러 관련 class가 있고, 특정 조건에 따라 어떤 class를 인스턴스화할지 결정하려는 경우에 특히 유용합니다. 다음과 같이 서로 다른 채널을 통해 message를 send할 수 있는 Notification 시스템을 생각해 보세요:
<?php
interface Notification {
public function send(string $message): string;
}
class EmailNotification implements Notification {
public function send(string $message): string {
return "Email: $message";
}
}
class SmsNotification implements Notification {
public function send(string $message): string {
return "SMS: $message";
}
}
factory가 없다면 곳곳에 if 문과 new 호출을 흩어 놓게 됩니다. factory는 이 로직을 중앙 집중화합니다:
<?php
class NotificationFactory {
public static function create(string $type): Notification {
return match($type) {
'email' => new EmailNotification(),
'sms' => new SmsNotification(),
default => throw new InvalidArgumentException("Unknown type: $type")
};
}
}
$notification = NotificationFactory::create('email');
echo $notification->send('Hello!');
출력:
Email: Hello!핵심 benefit은 코드가 구체적인 class가 아니라 Notification interface에 의존한다는 점입니다. 나중에 PushNotification class를 추가하더라도 factory만 업데이트하면 됩니다. factory를 사용하는 모든 코드는 수정 없이 새 유형에 자동으로 액세스할 수 있습니다.
챌린지
쉬움Factory Pattern을 사용하여 document generator system을 구축해 봅시다. 서로 다른 document type(PDF, HTML, Plain Text)은 공통 interface를 공유하지만 서로 다른 결과를 생성합니다. 따라서 object creation을 factory에서 중앙화하기에 완벽한 시나리오입니다.
코드를 네 개의 파일로 구성합니다.
Document.php: 모든 document type이 따라야 하는 contract를 정의하는Documentinterface를Create합니다. content를 받아 형식이 지정된 document 결과를 반환하는 단일methodrender(string $content): string을 가져야 합니다.Documents.php: Documentinterface를 포함하고 이를 구현하는 세 개의class를create합니다.PdfDocument: Itsrender()methodreturns"PDF: [content]"HtmlDocument: Itsrender()methodreturns"<html>[content]</html>"TextDocument: Itsrender()methodreturns"TXT: [content]"
DocumentFactory.php: Documents 파일을 포함하고 정적methodcreate(string $type): Document를 가진DocumentFactoryclass를create합니다. 이method는match를 사용하여 type에 따라 appropriate한 document object를return해야 합니다."pdf"는 새로운PdfDocument를return합니다."html"은 새로운HtmlDocument를return합니다."text"는 새로운TextDocument를return합니다.- 그 외의 type은
"Unknown document type: [type]"이라는message와 함께InvalidArgumentException을 발생시켜야 합니다.
main.php: DocumentFactory 파일을 포함합니다. 두 개의 입력, 즉 document type과 render할 content를 받습니다.factory를 사용하여 appropriate한 document type을
create한 다음, content와 함께 해당 객체의render()method를 Call하고 result를 print합니다.새로운 줄에
"Factory benefit: Adding new types only requires updating the factory"를 print하여 이 pattern이 valuable한 이유를 보여 줍니다.
Factory Pattern은 코드를 flexible하게 유지합니다. 나중에 MarkdownDocument를 추가해야 할 때는 factory만 업데이트하면 되며, 기존 코드는 모두 변경 없이 계속 작동합니다.
직접 해보기
<?php
require_once 'DocumentFactory.php';
// 입력 읽기
$type = trim(fgets(STDIN));
$content = trim(fgets(STDIN));
// TODO: DocumentFactory를 사용하여 적절한 문서 유형을 생성하세요
// TODO: content와 함께 render() 메서드를 호출하고 결과를 출력하세요
// TODO: On a new line, print "Factory benefit: Adding new types only requires updating the factory"
?>이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 PHP 컴파일러