Facade Pattern

The Facade Pattern is a structural design pattern that provides a simplified interface to a complex system of classes, making it easier to use.

In the context of Angular, the Facade Pattern can be useful for simplifying interactions with complex services or APIs.

Let's say you have a complex service in your Angular application that interacts with multiple other services or APIs.

Implementing a facade for this service can hide the complexity and provide a cleaner interface for other parts of your application to use.

Here's an example of how you can implement the Facade Pattern in Angular:

Suppose you have a complex service called DataService that interacts with multiple backend APIs and performs various data processing tasks.

You want to simplify the usage of this service by providing a facade for it.

// data.service.ts
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  // Imagine this service has complex methods for data fetching, processing, etc.
  
  fetchData(): Promise<any> {
    // Complex logic to fetch data from backend API
    return Promise.resolve({ data: 'Some data' });
  }

  processData(data: any): void {
    // Complex logic to process data
    console.log('Data processed:', data);
  }
}

Now, let's create a facade for the DataService:

// data-facade.service.ts
import { Injectable } from '@angular/core';
import { DataService } from './data.service';

@Injectable({
  providedIn: 'root'
})
export class DataFacadeService {
  constructor(private dataService: DataService) {}

  // Facade method to fetch and process data
  fetchDataAndProcess(): void {
    this.dataService.fetchData()
      .then((data) => {
        this.dataService.processData(data);
      })
      .catch((error) => {
        console.error('Error fetching data:', error);
      });
  }
}

Now, other components or services in your Angular application can use the DataFacadeService instead of directly interacting with the DataService.

This simplifies the usage and hides the complexity of the DataService:

// some.component.ts
import { Component, OnInit } from '@angular/core';
import { DataFacadeService } from './data-facade.service';

@Component({
  selector: 'app-some',
  templateUrl: './some.component.html',
  styleUrls: ['./some.component.css']
})
export class SomeComponent implements OnInit {
  constructor(private dataFacadeService: DataFacadeService) {}

  ngOnInit(): void {
    // Using the facade to fetch and process data
    this.dataFacadeService.fetchDataAndProcess();
  }
}

By using the Facade Pattern, you encapsulate the complexity of the DataService behind a simpler interface provided by the DataFacadeService, making it easier to use and maintain in your Angular application.

Last updated