设计模式二十一之桥接模式

通过理论,代码示例,Android源码来学习桥接模式

介绍

桥接模式(BridgePattern)也称为桥梁模式,是结构型模式之一。在现实生活中大家都知道 ”桥梁“ 是连接河道两岸的主要交通枢纽,简而言之其作用就是连接河的两边,而我们的桥接模式与现实中的情况很相似,也是承担着连接 ”两边“ 的作用,那么具体是哪两边呢?这里先不着急,我们先来看看定义吧。

定义

将抽象部分与实现部分分离,使它们都可以独立地进行变化。

使用场景

从模式的定义中我们大致可以了解到,这里的 ”桥梁“ 的作用其实就是连接 ”抽象部分“ 与 “实现部分”,但是事实上,任何多维度变化类或者说多个树状类之间的耦合都可以使用桥接模式来实现解耦。

UML 类图

  • Abstraction: 抽象部分
  • RefinedAbstraction: 优化的抽象部分
  • Implementor: 实现部分
  • ConcreteImplementorA/B: 实现部分的具体实现。
  • Client: 客户类,客户端程序。

代码示例

需求背景: 我们去店里面买咖啡,对不同的咖啡不同的定义。

咖啡抽象类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public abstract class coffee {


protected CoffeeAdditives impl;

public coffee(CoffeeAdditives impl) {
this.impl = impl;
}

/**
* 制作什么得咖啡由子类决定
*/
public abstract void makeCoffee();
}

大杯咖啡制作具体类:

1
2
3
4
5
6
7
8
9
10
11
public class LargeCoffee  extends coffee{
public LargeCoffee(CoffeeAdditives impl) {
super(impl);
}

@Override
public void makeCoffee() {
System.out.println("制作大杯咖啡->" + impl.addSomething());

}
}

小杯咖啡制作具体类:

1
2
3
4
5
6
7
8
9
10
public class SmallCoffee extends coffee {
public SmallCoffee(CoffeeAdditives impl) {
super(impl);
}

@Override
public void makeCoffee() {
System.out.println("制作小杯咖啡"+ impl.addSomething());
}
}

咖啡加糖/原味抽象类:

1
2
3
4
public interface CoffeeAdditives {

public String addSomething();
}

咖啡加糖/原味具体类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Ordinary implements CoffeeAdditives {
@Override
public String addSomething() {
return "原味";
}
}

复制代码
public class Sugar implements CoffeeAdditives {
@Override
public String addSomething() {
return "加糖";
}
}

test:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Test
public void testBridge(){
//原味
CoffeeAdditives coffeeAdditives = new Ordinary();
//加糖
CoffeeAdditives coffeeAdditives1 = new Sugar();
//大杯原味
LargeCoffee largeCoffee = new LargeCoffee(coffeeAdditives);
largeCoffee.makeCoffee();
//小杯原味
SmallCoffee smallCoffee = new SmallCoffee(coffeeAdditives);
smallCoffee.makeCoffee();

//大杯加糖
LargeCoffee largeCoffee2 = new LargeCoffee(coffeeAdditives1);
largeCoffee2.makeCoffee();
//小杯加糖
SmallCoffee smallCoffee3 = new SmallCoffee(coffeeAdditives1);
smallCoffee3.makeCoffee();
}

output:

1
2
3
4
制作大杯咖啡->原味
制作小杯咖啡原味
制作大杯咖啡->加糖
制作小杯咖啡加糖

从上面代码可以知道,不管 Coffee 变化了还是 CoffeeAdditives 变化了,其相对于对方而言都是独立的没有什么过多的交集,两者之间唯一的联系就是 Coffee 中保持的对 Coffeeadditives 的引用,就是开头介绍所说的枢纽,这就是桥接模式的简单示例。

总结

优点:

  • 分离抽象与实现、灵活的扩展。

缺点:

  • 不容易设计。
坚持原创技术分享,您的支持将鼓励我继续创作!