本文已参与[新人创作礼]活动,一起开启掘金创作之路
1. 概念
将抽象与实现分离,使它们可以独立变化.它是用组合关系代替继承关系来实现,从而降低了抽象和实现这连个可变维度的耦合度。 桥接模式遵循了里氏替换原则和依赖倒置原则,最终实现了开闭原则,对修改关闭,对扩展开放。
2. 优点
- 抽象与实现分离,扩展能力强
- 符合开闭原则
- 符合合成复用原则
- 其实现细节对客户透明
3. 缺点
由于聚合关系建立在抽象层,要求开发者针对抽象化进行设计与编程,能正确地识别出系统中两个独立变化的维度,这增加了系统的理解与设计难度。
4. 结构与实现
可以将抽象化部分与实现化部分分开,取消二者的继承关系,改用组合关系。
4.1 结构
主要角色:
- 抽象化角色:定义抽象类,并包含一个对实现化对象的引用。
- 扩展抽象化角色:是抽象化角色的子类,实现父类中的业务方法,并通过组合关系调用实现化角色中的业务方法。
- 实现化角色:定义实现化角色的接口,供扩展抽象化角色调用。
- 具体实现化角色:给出实现化角色接口的具体实现。
4.2 实现
//实现化角色
public interface Implementor {
void operation();
}
//具体实现化角色 蓝色
public class Blue implements Implementor {
@Override
public void operation() {
System.out.println("这只笔是蓝色的");
}
}
//具体实现化角色 红色
public class Red implements Implementor {
@Override
public void operation() {
System.out.println("这只笔是红色的");
}
}
//抽象化角色 笔
public abstract class Abstraction {
protected Implementor implementor;
protected Abstraction(Implementor implementor) {
this.implementor = implementor;
}
public abstract void operation(); //用笔写字
}
//扩展抽象化角色1 钢笔
public class RefinedAbstraction1 extends Abstraction {
protected RefinedAbstraction1(Implementor implementor) {
super(implementor);
}
@Override
public void operation() {
System.out.println("用钢笔写字");
implementor.operation(); //笔的颜色
}
}
//扩展抽象化角色2 毛笔
public class RefinedAbstraction2 extends Abstraction {
protected RefinedAbstraction2(Implementor implementor) {
super(implementor);
}
@Override
public void operation() {
System.out.println("用毛笔写字");
implementor.operation(); //笔的颜色
}
}
测试
public class BridgeTest {
@Test
public void test1() {
Implementor red = new Red();
Implementor blue = new Blue();
Abstraction gangbi = new RefinedAbstraction1(red);
Abstraction maobi = new RefinedAbstraction2(blue);
gangbi.operation();
maobi.operation();
}
}