---
title: "桥接模式（Bridge）"
author: "ldaolong"
date: "2014-09-15T16:19:42Z"
tags: []
categories: ["非技术"]
slug: "bridge"
draft: false
lastmod: "2014-09-15T16:19:42Z"
id: 2116694
url: "https://ldaolong.iteye.com/blog/2116694"
---

**桥接模式（Bridge）**

桥接模式就是把事物和其具体实现分开，使他们可以各自独立的变化。桥接的用意是：**将抽象化与实现化解耦，使得二者可以独立变化**，像我们常用的JDBC桥DriverManager一样，JDBC进行连接数据库的时候，在各个数据库之间进行切换，基本不需要动太多的代码，甚至丝毫不用动，原因就是JDBC提供统一接口，每个数据库提供各自的实现，用一个叫做数据库驱动的程序来桥接就行了。我们来看看关系图：

![](http://dl.iteye.com/upload/attachment/0083/1201/35f0b172-b976-3757-bb51-c65d5c9ce68e.jpg)

实现代码：

先定义接口：

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8239539 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8239539 "copy")

1. public interface Sourceable {
2. public void method();
3. }

分别定义两个实现类：

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8239539 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8239539 "copy")

1. public class SourceSub1 implements Sourceable {
2. @Override
3. public void method() {
4. System.out.println("this is the first sub!");
5. }
6. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8239539 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8239539 "copy")

1. public class SourceSub2 implements Sourceable {
2. @Override
3. public void method() {
4. System.out.println("this is the second sub!");
5. }
6. }

定义一个桥，持有Sourceable的一个实例：

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8239539 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8239539 "copy")

01. public abstract class Bridge {
02. private Sourceable source;
03. public void method(){
04. source.method();
05. }
06. public Sourceable getSource() {
07. return source;
08. }
09. public void setSource(Sourceable source) {
10. this.source = source;
11. }
12. }

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8239539 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8239539 "copy")

1. public class MyBridge extends Bridge {
2. public void method(){
3. getSource().method();
4. }
5. }

测试类：

**\[java]** [view plain](http://blog.csdn.net/zhangerqing/article/details/8239539 "view plain")[copy](http://blog.csdn.net/zhangerqing/article/details/8239539 "copy")

01. public class BridgeTest {
02. public static void main(String\[] args) {
03. Bridge bridge = new MyBridge();
04. /\*调用第一个对象\*/
05. Sourceable source1 = new SourceSub1();
06. bridge.setSource(source1);
07. bridge.method();
08. /\*调用第二个对象\*/
09. Sourceable source2 = new SourceSub2();
10. bridge.setSource(source2);
11. bridge.method();
12. }
13. }

output：

this is the first sub!  
this is the second sub!

这样，就通过对Bridge类的调用，实现了对接口Sourceable的实现类SourceSub1和SourceSub2的调用。接下来我再画个图，大家就应该明白了，因为这个图是我们JDBC连接的原理，有数据库学习基础的，一结合就都懂了。

![](http://dl.iteye.com/upload/attachment/0083/1203/6f713d07-1409-3312-99c9-fa6b0909f0b2.jpg)