桥接模式(Bridge Pattern)

2024/3/27 Java进阶

桥接模式:目的是将抽象与实现分离,使它们可以独立地变化。

# 1、桥接模式案例

将品牌和电脑分离,可以独立组合案例。

品牌

public interface Brand {
    public void brandInfo();
}

public class Apple implements Brand{
    @Override
    public void brandInfo() {
        System.out.print("苹果");
    }
}

public class HuaWei implements Brand{
    @Override
    public void brandInfo() {
        System.out.print("华为");
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

电脑:自带品牌

public abstract class Computer {
    // 电脑自带品牌
    protected Brand brand;

    public Computer(Brand brand) {
        this.brand = brand;
    }

    public abstract void info();
}
1
2
3
4
5
6
7
8
9
10

电脑类型

public class BotebookComputer extends Computer{

    public BotebookComputer(Brand brand) {
        super(brand);
    }

    @Override
    public void info() {
        brand.brandInfo();
        System.out.println("笔记本电脑");
    }
}

public class DesktopComputer extends Computer{

    public DesktopComputer(Brand brand) {
        super(brand);
    }

    @Override
    public void info() {
        brand.brandInfo();
        System.out.println("台式电脑");
    }
}
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
public class ClientTest {
    public static void main(String[] args) {
        // 华为笔记本
        BotebookComputer botebookComputer = new BotebookComputer(new HuaWei());
        botebookComputer.info();

        // 华为台式
        DesktopComputer desktopComputer = new DesktopComputer(new HuaWei());
        desktopComputer.info();

        // 苹果笔记本
        BotebookComputer apple1 = new BotebookComputer(new Apple());
        apple1.info();

        // 苹果台式
        DesktopComputer apple2 = new DesktopComputer(new Apple());
        apple2.info();
    }
}
/**
 * 华为笔记本电脑
 * 华为台式电脑
 * 苹果笔记本电脑
 * 苹果台式电脑
 * /
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