Member-only story
Essential Angular Design Patterns — Singleton, Observer, and Decorator
Design patterns are crucial for building scalable and maintainable Angular applications. In this two-part series, we explore the most impactful patterns. Let’s start with the Singleton, Observer, and Decorator patterns.
1. Singleton Pattern
Purpose: Ensures a class has only one instance throughout the application lifecycle.
Angular Use: Services provided with providedIn: ‘root’.
@Injectable({ providedIn: 'root' })
export class LoggerService {
log(message: string) {
console.log(message);
}
}
2. Observer Pattern
Purpose: Allows a one-to-many dependency where changes in one object notify all subscribers.
Angular Use: Reactive programming with RxJS to handle asynchronous events.
@Injectable({ providedIn: 'root' })
export class NotificationService {
private messageSubject = new Subject<string>();
message$ = this.messageSubject.asObservable();
sendMessage(message: string) {
this.messageSubject.next(message);
}
}
3. Decorator Pattern
Purpose: Dynamically adds functionality to classes, properties, or methods.
Angular Use: Metadata annotations like @Component, @Directive, and @Injectable
@Directive({ selector: '[appHighlight]' })
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}