Question
How can I utilize the factory pattern to create objects of different classes that accept varying parameters?
class Shape {
constructor(type) {
this.type = type;
}
}
class Circle extends Shape {
constructor(radius) {
super('Circle');
this.radius = radius;
}
}
class Square extends Shape {
constructor(side) {
super('Square');
this.side = side;
}
}
class ShapeFactory {
static createShape(type, dimension) {
switch(type) {
case 'circle':
return new Circle(dimension);
case 'square':
return new Square(dimension);
default:
throw new Error('Shape not recognized');
}
}
}
const circle = ShapeFactory.createShape('circle', 5);
const square = ShapeFactory.createShape('square', 4);
Answer
The Factory Pattern is a creational design pattern that allows for the creation of objects without having to specify the exact class of object that will be created. This pattern is particularly useful when dealing with classes that require different constructors due to varying parameters. By leveraging the Factory Pattern, we can abstract the instantiation logic and encapsulate the creation of objects based on specific conditions.
class ShapeFactory {
static createShape(type, dimension) {
switch(type) {
case 'circle':
return new Circle(dimension);
case 'square':
return new Square(dimension);
default:
throw new Error('Shape not recognized');
}
}
}
Causes
- Need for an object-oriented solution to manage the creation of instances with varied parameters.
- Simplifies object creation logic, allowing for cleaner and more maintainable code.
- Encourages adherence to the Open/Closed Principle, making the system extensible.
Solutions
- Define a Factory class responsible for creating instances based on input parameters.
- Utilize a switch statement or conditional logic in the factory method to handle different types of objects.
- Ensure that the Factory method can accept parameters dynamically to cater to varying constructor needs.
Common Mistakes
Mistake: Not managing parameter types correctly in the factory method.
Solution: Ensure that the factory method checks and validates the parameter types before instantiation.
Mistake: Forgetting to handle edge cases in shape creation.
Solution: Include error handling for unsupported shape types in the factory method.
Helpers
- Factory Pattern
- Factory Method
- Object Creation
- Design Patterns in JavaScript
- Programming Best Practices