Java 之 23 种设计模式解析——10、桥接模式(Bridge)

10、桥接模式(Bridge)

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

实现代码:

先定义接口:

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

分别定义两个实现类:

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

 

定义一个桥,持有Sourceable的一个实例:

1. public abstract class Bridge {
2.	private Sourceable source;
3.
4.	public void method(){
5.	source.method();
6.		}
7.
8.	public Sourceable getSource() {
9.	return source;
10.	}
11.
12.	public void setSource(Sourceable source) {
13.	this.source = source;
14.	}
15. }
1. public class MyBridge extends Bridge {
2.	public void method(){
3.	getSource().method();
4.		}
5.	}	

测试类:

1. public class BridgeTest {
2.
3.	public static void main(String[] args) {
4.
5.	Bridge bridge = new MyBridge();
6.
7.	/*调用第一个对象*/
8.	Sourceable source1 = new SourceSub1();
9.	bridge.setSource(source1);
10.	bridge.method();
11.
12.	/*调用第二个对象*/
13.	Sourceable source2 = new SourceSub2();
14.	bridge.setSource(source2);
15.	bridge.method();
16.	}
17. }

output:

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

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

目录:(点击进入相应页面)

概述、六大原则

一、创建模式

0、简单工厂模式

1.工厂方法模式(Factory Method)

2、抽象工厂模式

3、单例模式(Singleton)

4、建造者模式(Builder)

5、原型模式(Prototype)

二、结构模式(7种)

6、适配器模式

7、装饰模式(Decorator)

8、代理模式(Proxy)

9、外观模式(Facade)

10、桥接模式(Bridge)

11、组合模式(Composite

12、享元模式(Flyweight)

三、关系模式(11种)

13、策略模式(strategy)

14、模板方法模式(Template Method)

15、观察者模式(Observer)

16、迭代子模式(Iterator)

17、责任链模式(Chain of Responsibility)

18、命令模式(Command)

19、备忘录模式(Memento

20、状态模式(State)

21、访问者模式(Visitor)

22、中介者模式(Mediator)

23、解释器模式(Interpreter)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值