我是靠谱客的博主 哭泣白云,这篇文章主要介绍【设计模式】桥接模式,现在分享给大家,希望可以做个参考。

1. 分类

  • 结构型模式
    • 核心作用:是从程序的结构上实现松耦合,从而可以扩大整体的类结构,用来解决更大的问题
    • 分类:
      • 适配器模式、代理模式、桥接模式、装饰模式、组合模式、外观模式、享元模式

2. 简介

在这里插入图片描述
我们可用多层继承结构实现上图的关系

  • 问题:
    • 扩展性问题(类个数膨胀问题):
      • 如果要增加一个新的电脑类型:智能手机,则要增加各个品牌下面的类
      • 如果要增加一个新的品牌,也要增加各种电脑类型的类
    • 违反单一职责原则:
      • 一个类:联想笔记本,有两个引起这个类变化的原因

  • 桥接模式核心要点:
    • 处理多层继承结构,处理多维度变化的场景,将各个维度设计成独立的继承结构,使各个维度可以独立的扩展在抽象层建立关联

3. 代码测试

创建电脑品牌

复制代码
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
/** * 电脑品牌(新增品牌的话实现此接口即可,电脑类型无需改动) */ public interface Brand { void sale(); } /** * Lenovo品牌 */ class Lenovo implements Brand { @Override public void sale() { System.out.println("Lenovo.sale()"); } } /** * Dell品牌 */ class Dell implements Brand { @Override public void sale() { System.out.println("Dell.sale()"); } }

创建电脑类型

复制代码
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
/** * 电脑类型(新增类型的话继承此类即可,电脑品牌无需改动) */ public class Computer { protected Brand brand; public Computer(Brand brand) { super(); this.brand = brand; } public void sale() { brand.sale(); } } /** * 台式 */ class Desktop extends Computer { public Desktop(Brand brand) { super(brand); } @Override public void sale() { super.sale(); System.out.println("Desktop.sale()"); } } /** * 笔记本 */ class Laptop extends Computer { public Laptop(Brand brand) { super(brand); } @Override public void sale() { super.sale(); System.out.println("Laptop.sale()"); } }

测试

复制代码
1
2
3
4
5
6
7
8
public class Client { public static void main(String[] args) { // 销售Lenovo笔记本 Computer lenovo = new Laptop(new Lenovo()); lenovo.sale(); } }

控制台打印

复制代码
1
2
3
Lenovo.sale() Laptop.sale()

  • 桥接模式总结:
    • 桥接模式可以取代多层继承的方案。多层继承违背了单一职责原则,复用性较差,类的个数也非常多。桥接模式可以极大的减少子类的个数,从而降低管理和维护的成本。
    • 桥接模式极大的提高了系统的可扩展性,在两个变化维度中任意一个维度,都不需要修改原有的系统,符合开闭原则。

最后

以上就是哭泣白云最近收集整理的关于【设计模式】桥接模式的全部内容,更多相关【设计模式】桥接模式内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(58)

评论列表共有 0 条评论

立即
投稿
返回
顶部