10、桥接模式(Bridge)
来源:互联网 发布:burpsuite mac破解版 编辑:程序博客网 时间:2024/06/08 06:29
10、桥接模式(Bridge)
桥接模式就是把事物和其具体实现分开,使他们可以各自独立的变化。桥接的用意是:将抽象化与实现化解耦,使得二者可以独立变化,像我们常用的JDBC桥DriverManager一样,JDBC进行连接数据库的时候,在各个数据库之间进行切换,基本不需要动太多的代码,甚至丝毫不用动,原因就是JDBC提供统一接口,每个数据库提供各自的实现,用一个叫做数据库驱动的程序来桥接就行了。我们来看看关系图:
实现代码:
先定义接口:
1
2
3
public
interface
Sourceable {
public
void
method();
}
分别定义两个实现类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public
class
SourceSub1
implements
Sourceable {
@Override
public
void
method() {
System.out.println(
"this is the first sub!"
);
}
}
public
class
SourceSub2
implements
Sourceable {
@Override
public
void
method() {
System.out.println(
"this is the second sub!"
);
}
}
定义一个桥,持有Sourceable的一个实例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public
abstract
class
Bridge {
private
Sourceable source;
public
void
method(){
source.method();
}
public
Sourceable getSource() {
return
source;
}
public
void
setSource(Sourceable source) {
this
.source = source;
}
}
public
class
MyBridge
extends
Bridge {
public
void
method(){
getSource().method();
}
}
测试类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public
class
BridgeTest {
public
static
void
main(String[] args) {
Bridge bridge =
new
MyBridge();
/*调用第一个对象*/
Sourceable source1 = new SourceSub1();
bridge.setSource(source1);
bridge.method();
/*调用第二个对象*/
Sourceable source2 =
new
SourceSub2();
bridge.setSource(source2);
bridge.method();
}
}
output:
this is the first sub!
this is the second sub!
阅读全文
1 0
- 10、桥接模式(Bridge)
- 10、桥接模式(Bridge)
- 10、桥接模式(Bridge)
- 10 桥接模式(Bridge)
- 桥接模式(Bridge)
- 桥接模式(Bridge)
- Bridge(桥接模式)
- 桥接模式(Bridge)
- 桥接模式(Bridge)
- 桥接模式(Bridge)
- 桥接模式(Bridge)
- 桥接模式(Bridge)
- Bridge(桥接模式)
- 桥接模式(Bridge)
- 桥接模式(Bridge)
- 桥接模式(Bridge)
- 桥接模式(Bridge)
- 桥接模式(Bridge)
- myeclipse web project如何导入jar包
- 【笔记】利用ajax返回Html代替iframe,实现局部更新
- 9、外观模式(Facade)
- AAC规格(LC,HE,HEv2)及性能对比
- 使用baidu的api完成汉译英功能
- 10、桥接模式(Bridge)
- HTML Table锁定表头(CSS实现)
- 11、组合模式(Composite)
- CSS: 潜藏着的BFC
- bzoj3585mex
- 主页的制作
- android 获取apk的版本信息
- SDP协议小结
- Laravel 文件上传方法