Dezign Patterns
Bridge Design Pattern
The Bridge Pattern decouples an abstraction from its implementation so that the two can vary independently.
IntentThe Bridge Pattern decouples an abstraction from its implementation so that the two can vary independently.
Report abstraction can grow independently , like SalesReport, InvoiceReport ...
Exporter interface can grow independently , like CSVExporter, ExcelExporter ...
Participents
- Abstraction : defines the high-level interface and has a reference to Implementor.
- RefinedAbstraction : extends Abstraction and adds additional behavior.
- Implementor : is the interface for implementation classes.
- ConcreteImplementorA/B : implement the low-level platform-specific operations.
// Implementor
public interface Exporter {
void export(String fileName, Object data); // Object can be replaced with a stronger type later
}
// Concrete Implementor
public class CSVExporter implements Exporter {
@Override
public void export(String fileName, Object data) {
System.out.println("Exporting to CSV: " + fileName + ".csv");
// CSV export logic here
}
}
public class ExcelExporter implements Exporter {
@Override
public void export(String fileName, Object data) {
System.out.println("Exporting to Excel: " + fileName + ".xlsx");
// Excel export logic here
}
}
// Abstraction
public abstract class Report {
protected Exporter exporter;
public Report(Exporter exporter) {
this.exporter = exporter;
}
protected abstract Object generateData();
public void export(String fileName) {
Object data = generateData();
exporter.export(fileName, data);
}
}
// Concrete Abstraction
public class SalesReport extends Report {
public SalesReport(Exporter exporter) {
super(exporter);
}
@Override
protected Object generateData() {
return List.of(
Map.of("product", "Widget", "quantity", 10, "total", 100),
Map.of("product", "Gadget", "quantity", 5, "total", 75)
);
}
}
public class InvoiceReport extends Report {
public InvoiceReport(Exporter exporter) {
super(exporter);
}
@Override
protected Object generateData() {
return List.of(
Map.of("invoiceId", "INV001", "amount", 250, "customer", "John"),
Map.of("invoiceId", "INV002", "amount", 150, "customer", "Alice")
);
}
}
public class Main {
public static void main(String[] args) {
Exporter csvExporter = new CSVExporter();
Exporter excelExporter = new ExcelExporter();
Report salesReport = new SalesReport(csvExporter);
salesReport.export("sales_report");
Report invoiceReport = new InvoiceReport(excelExporter);
invoiceReport.export("invoice_report");
}
}