目的

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

类图

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

桥接模式.png

实现

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. }
  6. public class Sony extends TV {
  7. @Override
  8. public void on() {
  9. System.out.println("Sony.on()");
  10. }
  11. @Override
  12. public void off() {
  13. System.out.println("Sony.off()");
  14. }
  15. @Override
  16. public void tuneChannel() {
  17. System.out.println("Sony.tuneChannel()");
  18. }
  19. }
  20. public class RCA extends TV {
  21. @Override
  22. public void on() {
  23. System.out.println("RCA.on()");
  24. }
  25. @Override
  26. public void off() {
  27. System.out.println("RCA.off()");
  28. }
  29. @Override
  30. public void tuneChannel() {
  31. System.out.println("RCA.tuneChannel()");
  32. }
  33. }
  34. public abstract class RemoteControl {
  35. protected TV tv;
  36. public RemoteControl(TV tv) {
  37. this.tv = tv;
  38. }
  39. public abstract void on();
  40. public abstract void off();
  41. public abstract void tuneChannel();
  42. }
  43. public class ConcreteRemoteControl1 extends RemoteControl {
  44. public ConcreteRemoteControl1(TV tv) {
  45. super(tv);
  46. }
  47. @Override
  48. public void on() {
  49. System.out.println("ConcreteRemoteControl1.on()");
  50. tv.on();
  51. }
  52. @Override
  53. public void off() {
  54. System.out.println("ConcreteRemoteControl1.off()");
  55. tv.off();
  56. }
  57. @Override
  58. public void tuneChannel() {
  59. System.out.println("ConcreteRemoteControl1.tuneChannel()");
  60. tv.tuneChannel();
  61. }
  62. }
  63. public class ConcreteRemoteControl2 extends RemoteControl {
  64. public ConcreteRemoteControl2(TV tv) {
  65. super(tv);
  66. }
  67. @Override
  68. public void on() {
  69. System.out.println("ConcreteRemoteControl2.on()");
  70. tv.on();
  71. }
  72. @Override
  73. public void off() {
  74. System.out.println("ConcreteRemoteControl2.off()");
  75. tv.off();
  76. }
  77. @Override
  78. public void tuneChannel() {
  79. System.out.println("ConcreteRemoteControl2.tuneChannel()");
  80. tv.tuneChannel();
  81. }
  82. }
  83. public class Client {
  84. public static void main(String[] args) {
  85. RemoteControl remoteControl1 = new ConcreteRemoteControl1(new RCA());
  86. remoteControl1.on();
  87. remoteControl1.off();
  88. remoteControl1.tuneChannel();
  89. RemoteControl remoteControl2 = new ConcreteRemoteControl2(new Sony());
  90. remoteControl2.on();
  91. remoteControl2.off();
  92. remoteControl2.tuneChannel();
  93. }
  94. }

JDK中的体现

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