设计模式(二十三)—— 桥接模式

桥接模式

定义

将抽象和实现解耦,使他们可以独立变化。用组合关系代替继承关系来实现,从而降低了抽象和实现这两个可变维度的耦合度。

  • Abstraction:抽象化角色,主要职责是定义出该角色的行为,同事保存一个对实现化角色的引用。
  • Implementor:实现化角色,定义角色必需的行为和属性。
  • RefinedAbstraction:修正抽象化角色,引用实现划角色对抽象化角色进行修正。
  • ConcreteImplementor:具体实现化角色,实现接口或抽象类定义的方法和属性。

抽象角色引用实现角色,或者说抽象角色的部分实现是由实现角色完成的。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
public interface Implementor {
void doSomething();
void doAnything();
}

public class ConcreteImplementor1 implements Implementor {
@Override
public void doSomething() {
System.out.println("具体实现角色1 处理业务1");
}

@Override
public void doAnything() {
System.out.println("具体实现角色1 处理业务2");
}
}

public class ConcreteImplementor2 implements Implementor {
@Override
public void doSomething() {
System.out.println("具体实现角色2 处理业务1");
}

@Override
public void doAnything() {
System.out.println("具体实现角色2 处理业务2");
}
}

public abstract class Abstraction {

protected Implementor implementor;

public Abstraction(Implementor implementor) {
this.implementor = implementor;
}

abstract void operation();
}

public class ConcreteAbstraction extends Abstraction{

public ConcreteAbstraction(Implementor implementor) {
super(implementor);
}

@Override
void operation() {
System.out.println("具体抽象角色处理");
super.implementor.doSomething();
super.implementor.doAnything();
}
}

public class Main {

public static void main(String[] args) {
Implementor implementor = new ConcreteImplementor1();
Abstraction abstraction = new ConcreteAbstraction(implementor);
abstraction.operation();
Implementor implementor2 = new ConcreteImplementor2();
Abstraction abstraction2 = new ConcreteAbstraction(implementor2);
abstraction2.operation();
}
}

// 输出
具体抽象角色处理
具体实现角色1 处理业务1
具体实现角色1 处理业务2
具体抽象角色处理
具体实现角色2 处理业务1
具体实现角色2 处理业务2

优点

  • 抽象和实现分离,扩展能力好。

使用场景

  • 不希望或不适用使用继承的场景。
  • 接口或抽象类不稳定的场景。
  • 重要性要求较高的场景。

代码:GitHub


欢迎关注公众号:

https://raw.githubusercontent.com/lgsxiaosen/my_picture/master/article/%E6%89%AB%E7%A0%81_%E6%90%9C%E7%B4%A2%E8%81%94%E5%90%88%E4%BC%A0%E6%92%AD%E6%A0%B7%E5%BC%8F-%E6%A0%87%E5%87%86%E8%89%B2%E7%89%88.png

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
显示 Gitment 评论