factory-method
Define an interface for creating an object but let subclasses decide which class to instantiate.
SKILL.mdskills/code-quality/factory-method/SKILL.md
GitHubFactory Method
Defines a method for object creation in a base class, allowing subclasses to override which concrete class is instantiated. Decouples creator from product.
When to Use
- The exact type of object to create is not known until runtime
- Subclasses should control the type of objects they create
- You want to provide a library/framework extension point for object creation
- Constructor logic is complex and varies by context
How to Apply
- Define a common
Productinterface/abstract class - Create concrete product classes that implement
Product - Define a
Creatorabstract class with an abstractcreateProduct(): Productfactory method - Add default behaviour in
Creatorthat usescreateProduct() - Create concrete
Creatorsubclasses that overridecreateProduct()to return specific products
Example
interface Button { render(): void; onClick(f: () => void): void; }
class WindowsButton implements Button {
render() { console.log('Render Windows button'); }
onClick(f: () => void) { f(); }
}
class WebButton implements Button {
render() { console.log('<button>'); }
onClick(f: () => void) { document.addEventListener('click', f); }
}
abstract class Dialog {
abstract createButton(): Button; // factory method
render() { const btn = this.createButton(); btn.render(); }
}
class WindowsDialog extends Dialog { createButton() { return new WindowsButton(); } }
class WebDialog extends Dialog { createButton() { return new WebButton(); } }