桥接模式

连接两地的交通枢纽-桥接模式

介绍

桥接模式也称为桥梁模式,是结构型设计模式之一。

定义

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

使用场景

  1. 如果一个系统需要在构件的抽象化角色和具体化角色之间增加更多的灵活性,避免在两个层次之间建立静态的继承关系,可以通过桥接模式使它们在抽象层建立一个关联关系
  2. 对于那些不希望使用继承或因为多层次继承导致系统类的个数极具增加的系统,也可以考虑使用桥接模式
  3. 一个类存在两个独立变化的维度,且这两个维度都需要进行拓展

简单实现

咖啡抽象类:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
package BridgingMode;

public abstract class Coffee {
    protected CoffeeAdditives impl;

    public Coffee(CoffeeAdditives impl) {
        this.impl = impl;
    }
    public abstract void makeCoffee();
}

口味抽象类:

1
2
3
4
5
6
package BridgingMode;

public abstract class CoffeeAdditives {
    //咖啡添加
    public abstract String addSomeThing();
}

大杯咖啡:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
package BridgingMode;

public class LargeCoffee extends Coffee {
    public LargeCoffee(CoffeeAdditives impl) {
        super(impl);
    }

    public void makeCoffee() {
        System.out.println("大杯的"+impl+"咖啡");
    }
}

小杯咖啡:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
package BridgingMode;

public class SmallCoffee extends Coffee {
    public SmallCoffee(CoffeeAdditives impl) {
        super(impl);
    }

    public void makeCoffee() {
        System.out.println("小杯的"+impl+"咖啡");
    }
}

原味:

1
2
3
4
5
6
7
package BridgingMode;

public class Ordinary extends CoffeeAdditives {
    public String addSomeThing() {
        return "原味";
    }
}

加糖:

1
2
3
4
5
6
7
package BridgingMode;

public class Sugar extends CoffeeAdditives {
    public String addSomeThing() {
        return "加糖";
    }
}

测试类

 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
package BridgingMode;

public class Test {
    public static void main(String[] args) {
        //原汁原味
        Ordinary ordinary=new Ordinary();
        //准备糖类
        Sugar sugar=new Sugar();

        //大杯咖啡,原味
        LargeCoffee coffee1=new LargeCoffee(ordinary);
        coffee1.makeCoffee();
        //小杯咖啡,原味
        SmallCoffee coffee2=new SmallCoffee(ordinary);
        coffee2.makeCoffee();

        //大杯咖啡,加糖
        LargeCoffee largeCoffee=new LargeCoffee(sugar);
        largeCoffee.makeCoffee();
        //小杯咖啡,加糖
        SmallCoffee smallCoffee=new SmallCoffee(sugar);
        smallCoffee.makeCoffee();

    }
}

输出结果

65144.png

总结

优点

​ 分离抽象与实现、灵活的拓展以及对客户来说透明的实现等,

缺点

​ 不容易设计,对开发者来说有一定的经验要求。因此,对桥接模式来说,理解很简单,设计却不容易。