Fork me on GitHub

抽象与实现之间的桥梁-桥接模式

桥梁的作用其实就是连接“抽象部分”与“实现部分”,任何多维度变化类或者说树状类之间的耦合都可以使用桥接模式来进行解耦

生活中桥接模式也十分地常见,例如咖啡的种类,电源插头的使用等等,这里就举一个咖啡的例子,由它来实现桥接模式

咖啡与糖的关系是多对多的,我们需要先建立咖啡与糖的抽象类,咖啡抽象类依赖糖的抽象类

糖抽象类

1
2
3
public abstract class CoffeeAdditives {
public abstract String addSomething();
}

糖具体类

  1. 加糖

    1
    2
    3
    4
    5
    6
    public class Sugar extends CoffeeAdditives {
    @Override
    public String addSomething() {
    return "add sugar";
    }
    }
  2. 不加糖

    1
    2
    3
    4
    5
    6
    public class Ordinary extends CoffeeAdditives {
    @Override
    public String addSomething() {
    return "ordinary";
    }
    }

咖啡抽象类

1
2
3
4
5
6
7
8
public abstract class Coffee {
protected CoffeeAdditives coffeeAdditives;
public Coffee(CoffeeAdditives coffeeAdditives) {
this.coffeeAdditives = coffeeAdditives;
}

public abstract void makeCoffee();
}

具体咖啡类

  1. 大杯咖啡
1
2
3
4
5
6
7
8
9
10
public class LargeCoffee extends Coffee {
public LargeCoffee(CoffeeAdditives coffeeAdditives) {
super(coffeeAdditives);
}

@Override
public void makeCoffee() {
System.out.println("large " + coffeeAdditives.addSomething() + " coffee");
}
}
  1. 小杯咖啡
1
2
3
4
5
6
7
8
9
10
public class SmallCoffee extends Coffee {
public SmallCoffee(CoffeeAdditives coffeeAdditives) {
super(coffeeAdditives);
}

@Override
public void makeCoffee() {
System.out.println("small " + coffeeAdditives.addSomething() + " coffee");
}
}

使用如下

1
2
3
4
5
6
7
8
9
10
public class Main {
public static void main(String[] args) {
Ordinary ordinary = new Ordinary();
Sugar sugar = new Sugar();
LargeCoffee largeCoffee = new LargeCoffee(ordinary);
largeCoffee.makeCoffee();
SmallCoffee smallCoffee = new SmallCoffee(sugar);
smallCoffee.makeCoffee();
}
}