桥接模式(Bridge)
来源:互联网 发布:孕妇装比较好的淘宝店 编辑:程序博客网 时间:2024/06/06 00:13
桥接模式就是把事物和其具体实现分开,使他们可以各自独立的变化。桥接的用意是:将抽象化与实现化解耦,使得二者可以独立变化,像我们常用的JDBC桥DriverManager一样,JDBC进行连接数据库的时候,在各个数据库之间进行切换,基本不需要动太多的代码,甚至丝毫不用动,原因就是JDBC提供统一接口,每个数据库提供各自的实现,用一个叫做数据库驱动的程序来桥接就行了。
实现代码:
先定义接口:
[java] view plaincopy
- public interface Sourceable {
- public void method();
- }
分别定义两个实现类:
[java] view plaincopy
- public class SourceSub1 implements Sourceable {
- @Override
- public void method() {
- System.out.println("this is the first sub!");
- }
- }
[java] view plaincopy
- public class SourceSub2 implements Sourceable {
- @Override
- public void method() {
- System.out.println("this is the second sub!");
- }
- }
定义一个桥,持有Sourceable的一个实例:
[java] view plaincopy
- 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;
- }
- }
[java] view plaincopy
- public class MyBridge extends Bridge {
- public void method(){
- getSource().method();
- }
- }
测试类:
[java] view plaincopy
- 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!
这样,就通过对Bridge类的调用,实现了对接口Sourceable的实现类SourceSub1和SourceSub2的调用。
0 0
- 桥接模式(Bridge)
- 桥接模式(Bridge)
- Bridge(桥接模式)
- 桥接模式(Bridge)
- 桥接模式(Bridge)
- 桥接模式(Bridge)
- 桥接模式(Bridge)
- 桥接模式(Bridge)
- Bridge(桥接模式)
- 桥接模式(Bridge)
- 桥接模式(Bridge)
- 桥接模式(Bridge)
- 桥接模式(Bridge)
- 桥接模式(Bridge)
- 桥接模式(Bridge)
- 桥接模式(Bridge)
- 桥接模式(Bridge)
- 桥接模式(Bridge)
- nagios插件之监控日志中CASA接口响应时间
- Delphi中的Val函数和iif函数
- SuperIndicator 专做轮播图库,没有之一,支持无限循环
- std::sort引发的core
- Spinner下拉列表的学习心得
- 桥接模式(Bridge)
- Ubuntu14.04全分布式安装hadoop2.7.2(二)下载安装+ssh免密码登陆
- NS2 学习资料网站链接
- leetcode(40).160. Intersection of Two Linked Lists
- CVPR 2016-11-18
- [iOS]UINavigationController全屏pop之为控制器添加左滑push
- forward 和redirect的区别
- MVC在Android中的应用
- 彩笔笔记2016/11/23——创建用户与配置挂载新硬盘