Implement Factory pattern
✓Works with OpenClaudeYou are a software architect implementing the Factory design pattern. The user wants to create a flexible object creation mechanism that decouples client code from concrete class instantiation.
What to check first
- Identify the common interface or base class that all created objects will share
- Determine which concrete implementations need to be created and how they differ
- Verify the factory should be a simple function, class method, or dedicated factory class based on complexity
Steps
- Define a base class or interface that all products will implement—use
abstract classor TypeScriptinterfaceto enforce the contract - Create concrete classes that extend the base class and implement the required methods specific to each variant
- Build a factory function or factory class with a method that accepts a parameter identifying which concrete class to instantiate
- Use a
switchstatement,if/elsechain, or object map to route creation logic to the correct concrete class - Return an instance typed as the base class, not the concrete implementation, so callers depend only on the interface
- (Optional) For complex creation logic, extract it into a dedicated Factory class with a public
create()method - Update client code to call the factory instead of directly calling
new ConcreteClass() - Test that the factory returns the correct instance type and that polymorphic behavior works across all variants
Code
// Base class defining the interface
class Database {
connect() {
throw new Error('connect() must be implemented');
}
query(sql) {
throw new Error('query() must be implemented');
}
}
// Concrete implementations
class MySQLDatabase extends Database {
connect() {
return 'Connected to MySQL';
}
query(sql) {
return `Executing MySQL query: ${sql}`;
}
}
class PostgresDatabase extends Database {
connect() {
return 'Connected to PostgreSQL';
}
query(sql) {
return `Executing PostgreSQL query: ${sql}`;
}
}
class MongoDatabase extends Database {
connect() {
return 'Connected to MongoDB';
}
query(sql) {
return `Executing MongoDB query: ${sql}`;
}
}
// Factory function
function createDatabase(type) {
switch (type.toLowerCase()) {
case 'mysql':
return new MySQLDatabase();
case 'postgres':
return new PostgresDatabase();
case 'mongo':
return new MongoDatabase();
default:
throw new Error(`Unknown database type: ${type}`);
}
}
// Client code - no knowledge of concrete classes
const db1 = createDatabase('mysql');
console.log(db1.connect()); // 'Connected to MySQL'
console.log(db1.query('SELECT * FROM users')); // 'Executing MySQL query: SELECT * FROM users'
const db2 = createDatabase('postgres');
console.log(db2.connect()); // 'Connected to PostgreSQL'
console
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Architecture Skills
Other Claude Code skills in the same category — free to download.
Singleton Pattern
Implement Singleton pattern
Observer Pattern
Implement Observer/PubSub pattern
Strategy Pattern
Implement Strategy pattern
Repository Pattern
Implement Repository pattern for data access
Dependency Injection
Set up dependency injection
CQRS Setup
Implement CQRS pattern
Event Sourcing
Implement Event Sourcing pattern
Want a Architecture skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.