Bridge pattern comes under Structural design pattern.
Decouple an abstraction from its implementation so that the two can vary independently.
Behaviour & Advantages
Avoids permanent binding between an abstraction and an implementation.
Abstraction and implementation can vary independently.
Cleaner and loosely coupled client code.
Participants
Abstraction
Defines an abstract interface and holds a reference to Implementor.
It may be an interface or abstract class depending on the context.
Refined Abstraction
An extension or implementation of Abstraction.
Implementor
Defines an abstract interface for implementation classes.
Abstraction uses Implementor to perform some operation.
Concrete Implementor
An implementation of Implementor interface.
This example shows a simple payment system where user likes to pay his bills
using various payment methods.
Here IBill acts as Abstraction and IPayment acts as Implementor.
Classes PhoneBill, NewPhoneBill and WaterBill are Refined Abstractions.
The payment methods such as CreditCardPayment and DebitCardPayment
are Concrete Implementors.
We can observe that each Abstraction (PhoneBill, NewPhoneBill and WaterBill)
has a reference to an Implementor (either CreditCardPayment or DebitCardPayment).
The bill abstraction interface is shown below,
IBill [] bills = new IBill[] { new PhoneBill(2000, new DebitCardPayment()), new PhoneBill(40000, new CreditCardPayment()),
new NewPhoneBill(2000, 10, new DebitCardPayment()), new NewPhoneBill(40000, 20, new CreditCardPayment()),
new WaterBill(new DebitCardPayment()), new WaterBill(new CreditCardPayment())
};
for (IBill bill : bills) {
bill.pay();
}
}
}
It gives the following output,
Paid Rs.2000 with debit card for 'Phone Bill'
Paid Rs.40000 with credit card for 'Phone Bill'
Paid Rs.2200 with debit card for 'New Phone Bill'
Paid Rs.48000 with credit card for 'New Phone Bill'
Paid Rs.250 with debit card for 'Water Bill'
Paid Rs.250 with credit card for 'Water Bill'