需求:手机操作问题
传统方案解决手机操作问题
引出的问题
桥接模式:
基本介绍
桥接模式Bridge原理类图
原理:类图说明
1)Client 类:桥接模式的调用者
2)抽象类 (Abstraction) 维护了 Implementor ,即它的实现类 ConcreteImplementorA…, 二者是聚合关系 , Abstraction充当桥接类
桥接模式解决手机操作问题
类图
代码实现
Brand
//接口 public interface Brand { void open(); void close(); void call(); }
Vivo
public class Vivo implements Brand { @Override public void open() { // TODO Auto-generated method stub System.out.println(" Vivo手机开机 "); } @Override public void close() { // TODO Auto-generated method stub System.out.println(" Vivo手机关机 "); } @Override public void call() { // TODO Auto-generated method stub System.out.println(" Vivo手机打电话 "); } }
XiaoMi
public class XiaoMi implements Brand { @Override public void open() { // TODO Auto-generated method stub System.out.println(" 小米手机开机 "); } @Override public void close() { // TODO Auto-generated method stub System.out.println(" 小米手机关机 "); } @Override public void call() { // TODO Auto-generated method stub System.out.println(" 小米手机打电话 "); } }
Phone
public abstract class Phone { //组合品牌 private Brand brand; //构造器 public Phone(Brand brand) { super(); this.brand = brand; } protected void open() { this.brand.open(); } protected void close() { brand.close(); } protected void call() { brand.call(); } }
FoldedPhone
//折叠式手机类,继承 抽象类 Phone public class FoldedPhone extends Phone { //构造器 public FoldedPhone(Brand brand) { super(brand); } public void open() { super.open(); System.out.println(" 折叠样式手机 "); } public void close() { super.close(); System.out.println(" 折叠样式手机 "); } public void call() { super.call(); System.out.println(" 折叠样式手机 "); } }
UpRightPhone
public class UpRightPhone extends Phone { //构造器 public UpRightPhone(Brand brand) { super(brand); } public void open() { super.open(); System.out.println(" 直立样式手机 "); } public void close() { super.close(); System.out.println(" 直立样式手机 "); } public void call() { super.call(); System.out.println(" 直立样式手机 "); } }
Client
public class Client { public static void main(String[] args) { //获取折叠式手机 (样式 + 品牌 ) Phone phone1 = new FoldedPhone(new XiaoMi()); phone1.open(); phone1.call(); phone1.close(); System.out.println("======================="); Phone phone2 = new FoldedPhone(new Vivo()); phone2.open(); phone2.call(); phone2.close(); System.out.println("=============="); UpRightPhone phone3 = new UpRightPhone(new XiaoMi()); phone3.open(); phone3.call(); phone3.close(); System.out.println("=============="); UpRightPhone phone4 = new UpRightPhone(new Vivo()); phone4.open(); phone4.call(); phone4.close(); } }
运行结果:
应用
桥接模式在JDBC的源码剖析
桥接模式其它应用场景
桥接模式的注意事项和细节