Bridge Design Pattern
The Bridge design pattern is a structural pattern that helps separate an abstraction from its implementation, allowing both to evolve independently. It is useful when we have multiple dimensions of change in our system.
Key Concept
Abstraction: Defines the high-level control logic.
Implementation: Provides the concrete behaviour behind the abstraction.
The Bridge acts as an interface between these layers.
We can implement the Bridge pattern to decouple a high-level maps functionality from the underlying mapping provider (such as Google Maps). This setup allows us to easily swap out or extend providers (for example, to include ArcGIS Maps or OpenStreetMaps) without rewriting the application logic.
Step 1 : Define the Implementor Interface
//Implementor interface
export interface MapProvider {
initializeMap(elementId:string,center:{lat:number,lng:number},zoom:number):void;
addMarker(position: {lat:number,lng:number},title:string):void;
}
//This interface declares operations that concrete mapping providers must implement.
//The MapProvider interface defines a common structure for all map providers.
//This interface acts as the bridge that ensures all map providers implement the same methods.
MapProvider interface defines the implementation of the tasks needed from the map providers. Every map provider is supposed to initialise the map and add markers. The specific map provider that adheres to this required contract can do both the required jobs in a way that they like.
It’s the "engine" or "service" responsible for interfacing with specific map SDKs (Google Maps SDK, OpenStreetMap library, etc.).
Step 2: Create a Concrete Implementor for Google Maps
In this example, we will see a draft code of the Google Maps implementation for the sake of learning only. In an actual scenario, we require the Google Maps API Keys and other setup parameters that is vital for the implementation.
//Concrete Implementor
import { MapProvider } from "./MapProvider";
declare var google: any; // Assuming the Google Maps API is loaded
export class GoogleMapsProvider implements MapProvider {
private map:any;
initializeMap(elementId: string, center: { lat: number; lng: number; }, zoom: number): void {
this.map = new google.maps.Map(document