When building large-scale applications in Angular, managing object creation efficiently is crucial. The Factory Design Pattern provides a structured way to instantiate objects, reducing redundancy, improving maintainability, and enhancing scalability.
Instead of instantiating objects manually across components, the Factory Pattern centralizes the creation logic in a dedicated service.
const product = new SmartphoneProduct(1, 'iPhone 13', 999, 'smartphones');'
const product = productFactory.createProduct(data);
In an evolving Angular application, requirements change. With a Factory Pattern, you modify only one place (the factory service) when adding new object types.
You would need to modify everywhere products are created.
You only update ProductFactoryService
.
Without a factory, developers tend to add multiple *ngIf
conditions to handle different object types.
<p *ngIf="product.category === 'smartphones'">Final Price: {{ product.price * 1.1 }}</p>
<p *ngIf="product.category === 'laptops'">Final Price: {{ product.price * 0.9 }}</p>
calculateFinalPrice() {
return this.product.calculateFinalPrice();
}
“Open for extension, closed for modification.”
The Factory Pattern allows adding new types of objects without modifying existing logic.
Instead of modifying multiple files, you just add a new class.
case 'tablets':
return new TabletProduct(data.id, data.title, data.price, data.category);
The Factory Design Pattern in Angular helps in:
✔ Encapsulating object creation
✔ Reducing *ngIf
complexity in templates
✔ Following SOLID principles
✔ Enhancing maintainability and testability
By adopting the Factory Pattern, your Angular app becomes more scalable, modular, and easier to maintain! 🚀
import { Injectable } from "@angular/core";
import { SmartphoneProduct } from "../models/smartphone-product";
import { LaptopProduct } from "../models/laptop-product";
import { Product } from "../models/product";
@Injectable({
providedIn: "root",
})
export class ProductFactoryService {
createProduct(data: any): Product {
switch (data.category) {
case "smartphones":
return new SmartphoneProduct(data.id, data.title, data.price, data.category);
case "laptops":
return new LaptopProduct(data.id, data.title, data.price, data.category);
default:
throw new Error(`Unknown product category: ${data.category}`);
}
}
}
📌 connect with me on LinkedIn for more technical updates and content