Factory Method (Creational)
Intent / problem it solves
Let a type defer which concrete product to instantiate to subtypes. Callers depend on an interface or abstract creator operation instead of new ConcreteType() sprinkled everywhere.
When to use / when NOT
Use when creation rules vary by subclass, region, or feature flag, or when you want to swap families in one place.
Avoid when a single simple constructor suffices or when Abstract Factory fits multiple related products better.
Structure
Creator defines factoryMethod(); concrete creators return concrete products behind a common product interface.
Go example
package main
import "fmt"
type Notifier interface {
Send(text string)
}
type EmailNotifier struct{}
func (EmailNotifier) Send(text string) { fmt.Println("email:", text) }
type SMSNotifier struct{}
func (SMSNotifier) Send(text string) { fmt.Println("sms:", text) }
type AlertFactory interface {
Build() Notifier
}
type EmailFactory struct{}
func (EmailFactory) Build() Notifier { return EmailNotifier{} }
type SMSFactory struct{}
func (SMSFactory) Build() Notifier { return SMSNotifier{} }
func NotifyUser(factory AlertFactory, message string) {
notifier := factory.Build()
notifier.Send(message)
}
func main() {
NotifyUser(EmailFactory{}, "hello")
}JavaScript example
class Transport {
deliver(payload) {
throw new Error('override');
}
}
class HttpTransport extends Transport {
deliver(payload) {
return { channel: 'http', payload };
}
}
class GrpcTransport extends Transport {
deliver(payload) {
return { channel: 'grpc', payload };
}
}
class ClientFactory {
createTransport(kind) {
if (kind === 'http') return new HttpTransport();
if (kind === 'grpc') return new GrpcTransport();
throw new Error('unknown kind');
}
}
const factory = new ClientFactory();
const transport = factory.createTransport('grpc');
console.log(transport.deliver({ id: 1 }));Interview phrase
“Factory method keeps object creation in one place so I can swap implementations for tests or regions without changing the high-level flow that only knows the product interface.”
Related LLD case studies
Link from LLD solutions that create strategies or notifiers from configuration (e.g. payment provider, notification channel) in LLD case studies.
Last updated on
Spotted something unclear or wrong on this page?