In this example, let’s us see how to implement Bridge Pattern in Java.
Source Code
package com.beginner.examples;
// abstract mobile class
abstract class Mobile {
protected MobileSoft mobileSoft;
public void setMobileSoft(MobileSoft mobileSoft) {
this.mobileSoft = mobileSoft;
}
public abstract void run();
}
// detail mobile
class AppleMobile extends Mobile {
@Override
public void run() {
mobileSoft.run();
}
}
class SamsungMobile extends Mobile {
@Override
public void run() {
mobileSoft.run();
}
}
// interface
interface MobileSoft {
public void run();
}
class Photo implements MobileSoft{
@Override
public void run() {
System.out.println("photo");
}
}
class Game implements MobileSoft{
@Override
public void run() {
System.out.println("game");
}
}
public class BridgeExample {
public static void main(String[] args){
Mobile apple = new AppleMobile();
apple.setMobileSoft(new Photo());
apple.run();
Mobile samsung = new SamsungMobile();
samsung.setMobileSoft(new Game());
samsung.run();
}
}
Output:
photo
game