팩토리 패턴이란?
객체 생성 과정을 추상화 한것이다. 사용자는 어떤 객체를 생성할지, 어떻게 생성할지를 감추고 인터페이스만 제공하도록 한다.
FE에서 사용할 수 있는 패턴 적용은 아래와 같다.
만약에 Notification을 적용해야한다면 팩토리 패턴을 적용해서 구현할 수 있다.
만약에 App.jsx에서 알림이 오면 출력되는 기능을 구현하게 된다면, 알림 메세지의 종류 와 상관없이 Factory패턴을 적용해서 아래와 같이 간단하게 작성할 수 있다.
//App.jsx
import React from 'react';
import { NotificationFactory } from './NotificationFactory';
function App() {
return (
<div>
<h1>알림 테스트</h1>
{NotificationFactory(type, { message })}
</div>
);
}
팩토리 함수 구현 예시
import { WarningNotification } from './WarningNotification';
export function NotificationFactory(type, props) {
switch (type) {
case 'success':
return <SuccessNotification {...props} />;
case 'error':
return <ErrorNotification {...props} />;
case 'warning':
return <WarningNotification {...props} />;
default:
return null;
}
}
알림 메세지 구현
// SuccessNotification.jsx
export const SuccessNotification = ({ message }) => (
<div style={{ backgroundColor: 'green', color: 'white' }}>
✅ Success: {message}
</div>
);
// ErrorNotification.jsx
export const ErrorNotification = ({ message }) => (
<div style={{ backgroundColor: 'red', color: 'white' }}>
❌ Error: {message}
</div>
);
// WarningNotification.jsx
export const WarningNotification = ({ message }) => (
<div style={{ backgroundColor: 'orange', color: 'black' }}>
⚠️ Warning: {message}
</div>
);