桥接(Bridge)

Intent

将抽象与实现分离开来,使它们可以独立变化。

Class Diagram

  • Abstraction:定义抽象类的接口
  • Implementor:定义实现类接口

设计模式 - 桥接 - 图1

Implementation

RemoteControl 表示遥控器,指代 Abstraction。

TV 表示电视,指代 Implementor。

桥接模式将遥控器和电视分离开来,从而可以独立改变遥控器或者电视的实现。

  1. public abstract class TV {
  2. public abstract void on();
  3. public abstract void off();
  4. public abstract void tuneChannel();
  5. }
  1. public class Sony extends TV {
  2. @Override
  3. public void on() {
  4. System.out.println("Sony.on()");
  5. }
  6. @Override
  7. public void off() {
  8. System.out.println("Sony.off()");
  9. }
  10. @Override
  11. public void tuneChannel() {
  12. System.out.println("Sony.tuneChannel()");
  13. }
  14. }
  1. public class RCA extends TV {
  2. @Override
  3. public void on() {
  4. System.out.println("RCA.on()");
  5. }
  6. @Override
  7. public void off() {
  8. System.out.println("RCA.off()");
  9. }
  10. @Override
  11. public void tuneChannel() {
  12. System.out.println("RCA.tuneChannel()");
  13. }
  14. }
  1. public abstract class RemoteControl {
  2. protected TV tv;
  3. public RemoteControl(TV tv) {
  4. this.tv = tv;
  5. }
  6. public abstract void on();
  7. public abstract void off();
  8. public abstract void tuneChannel();
  9. }
  1. public class ConcreteRemoteControl1 extends RemoteControl {
  2. public ConcreteRemoteControl1(TV tv) {
  3. super(tv);
  4. }
  5. @Override
  6. public void on() {
  7. System.out.println("ConcreteRemoteControl1.on()");
  8. tv.on();
  9. }
  10. @Override
  11. public void off() {
  12. System.out.println("ConcreteRemoteControl1.off()");
  13. tv.off();
  14. }
  15. @Override
  16. public void tuneChannel() {
  17. System.out.println("ConcreteRemoteControl1.tuneChannel()");
  18. tv.tuneChannel();
  19. }
  20. }
  1. public class ConcreteRemoteControl2 extends RemoteControl {
  2. public ConcreteRemoteControl2(TV tv) {
  3. super(tv);
  4. }
  5. @Override
  6. public void on() {
  7. System.out.println("ConcreteRemoteControl2.on()");
  8. tv.on();
  9. }
  10. @Override
  11. public void off() {
  12. System.out.println("ConcreteRemoteControl2.off()");
  13. tv.off();
  14. }
  15. @Override
  16. public void tuneChannel() {
  17. System.out.println("ConcreteRemoteControl2.tuneChannel()");
  18. tv.tuneChannel();
  19. }
  20. }
  1. public class Client {
  2. public static void main(String[] args) {
  3. RemoteControl remoteControl1 = new ConcreteRemoteControl1(new RCA());
  4. remoteControl1.on();
  5. remoteControl1.off();
  6. remoteControl1.tuneChannel();
  7. RemoteControl remoteControl2 = new ConcreteRemoteControl2(new Sony());
  8. remoteControl2.on();
  9. remoteControl2.off();
  10. remoteControl2.tuneChannel();
  11. }
  12. }

JDK

  • AWT (It provides an abstraction layer which maps onto the native OS the windowing support.)
  • JDBC

设计模式 - 桥接 - 图2