Factory Pattern
A factory is a function or class that creates objects without exposing the creation logic. The caller asks for an object and receives one without knowing how it was built.
Function factory
ts
type NotificationType = 'success' | 'error' | 'warning' | 'info';
interface Notification {
id: string;
type: NotificationType;
message: string;
icon: string;
color: string;
duration: number;
}
function createNotification(type: NotificationType, message: string): Notification {
const base = { id: crypto.randomUUID(), message };
const config: Record<NotificationType, Omit<Notification, 'id' | 'message'>> = {
success: { type: 'success', icon: '✓', color: '#22c55e', duration: 3000 },
error: { type: 'error', icon: '✕', color: '#ef4444', duration: 5000 },
warning: { type: 'warning', icon: '!', color: '#f59e0b', duration: 4000 },
info: { type: 'info', icon: 'i', color: '#3b82f6', duration: 3000 },
};
return { ...base, ...config[type] };
}
// clean usage - no config knowledge needed
const n = createNotification('error', 'Something went wrong');React component factory
tsx
function createFormField(type: 'text' | 'email' | 'password' | 'tel') {
return function FormField({ label, ...props }: FormFieldProps) {
return (
<label>
{label}
<input type={type} {...props} />
</label>
);
};
}
const EmailField = createFormField('email');
const PasswordField = createFormField('password');
const PhoneField = createFormField('tel');API client factory
ts
function createApiClient(baseUrl: string, token: string) {
const headers = {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
};
return {
get: (path: string) => fetch(`${baseUrl}${path}`, { headers }),
post: (path: string, body: unknown) =>
fetch(`${baseUrl}${path}`, { method: 'POST', headers, body: JSON.stringify(body) }),
};
}
const api = createApiClient('https://api.example.com', userToken);
api.get('/users');Factory is one of the most natural patterns in JavaScript because functions are first-class. Any time you call a function to get back a configured object or component, you are using a factory.
updated
did you know it?