Factory Pattern
1. Introduction
The Factory Pattern is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created. It helps in managing and maintaining object creation in a clean and efficient way.
2. Key Concepts
2.1 Definition
A Factory Pattern defines an interface for creating an object, but it is the responsibility of the implementing classes to instantiate the appropriate class.
2.2 Types of Factory Patterns
- Simple Factory
- Factory Method
- Abstract Factory
3. Implementation
3.1 Simple Factory Example
class Shape {
constructor(type) {
this.type = type;
}
}
class ShapeFactory {
createShape(type) {
return new Shape(type);
}
}
// Usage
const factory = new ShapeFactory();
const circle = factory.createShape('Circle');
console.log(circle.type); // Circle
3.2 Factory Method Example
class Shape {
draw() {}
}
class Circle extends Shape {
draw() {
return 'Drawing a Circle';
}
}
class Square extends Shape {
draw() {
return 'Drawing a Square';
}
}
class ShapeFactory {
createShape(type) {
if (type === 'Circle') {
return new Circle();
} else if (type === 'Square') {
return new Square();
}
return null;
}
}
// Usage
const factory = new ShapeFactory();
const shape1 = factory.createShape('Circle');
console.log(shape1.draw()); // Drawing a Circle
const shape2 = factory.createShape('Square');
console.log(shape2.draw()); // Drawing a Square
4. Best Practices
- Prefer using Factory Method over Simple Factory for better flexibility.
- Use Abstract Factory when you need to create families of related objects.
- Keep the factory methods separate from the business logic.
5. FAQ
What is the main advantage of using the Factory Pattern?
The main advantage is that it promotes loose coupling and encapsulates the knowledge of which concrete classes to instantiate.
When should I use the Factory Pattern?
Use the Factory Pattern when the exact type of the object to be created is determined by the client at runtime, or when the process of creating an object is complex.