角色:
场景:多个品牌手机有着不同的样式,样式又对应着不同的品牌手机
定义行为实现类的接口
public interface Brand { void call(); void open(); void close(); }
定义了手机的操作行为,定义手机实现接口
public class Vivo implements Brand{ @Override public void call() { System.out.println("vivo手机打电话"); } @Override public void open() { System.out.println("vivo开机"); } @Override public void close() { System.out.println("vivo关机"); } }
public class XiaoMi implements Brand{ @Override public void call() { System.out.println("小米手机打电话"); } @Override public void open() { System.out.println("小米手机开机"); } @Override public void close() { System.out.println("小米手机关机"); } }
定义抽象类,聚合行为操作类的接口,这也就是桥接器
public abstract class Phone { private Brand brand; public Phone(Brand brand){ this.brand = brand; } protected void open(){ brand.open(); } protected void close(){ brand.close(); } protected void call(){ brand.call(); } }
定义桥接的实现
public class FoldedPhone extends Phone{ public FoldedPhone(Brand brand) { super(brand); } @Override public void open(){ super.open(); System.out.println("折叠样式手机"); } @Override public void close(){ super.close(); System.out.println("折叠样式手机"); } @Override public void call(){ super.call(); System.out.println("折叠样式手机"); } }
public class UpRightPhone extends Phone{ public UpRightPhone(Brand brand) { super(brand); } @Override public void open(){ super.open(); System.out.println("直立样式手机"); } @Override public void close(){ super.close(); System.out.println("直立样式手机"); } @Override public void call(){ super.call(); System.out.println("直立样式手机"); } }
客户端调用
public class Client { public static void main(String[] args) { // 获取折叠式手机,样式加品牌 FoldedPhone foldedPhone = new FoldedPhone(new XiaoMi()); foldedPhone.open(); foldedPhone.call(); foldedPhone.close(); System.out.println("------------"); foldedPhone = new FoldedPhone(new Vivo()); foldedPhone.open(); foldedPhone.call(); foldedPhone.close(); System.out.println("------------"); // 直立 UpRightPhone upRightPhone = new UpRightPhone(new XiaoMi()); upRightPhone.open(); upRightPhone.call(); upRightPhone.close(); } }
在这种模式下,我们新增手机只需要添加接口的实现类即可