这篇来聊一聊java设计模式之桥接模式。

桥接模式,就是把两个可以分离的类,连接起来,进行不同的组合,防止耦合度过大,导致代码维护困难。重点就是将抽象化与实现化脱耦,使得二者可以独立地变化。 昨天刚说完不喜欢说教,今天就开始了。 还是用比较幽默的方式说吧。 今天冬至,大家都吃饺子了没? 饺子有很多种口味啊!什么猪肉白菜的,牛肉茴香,什么素三鲜,一堆口味! 假设你刚吃完猪肉白菜,又想尝尝牛肉白菜! 厨师也是人啊,能不能不这么折腾他! 最理想的办法就是,我把素菜放到一块,肉馅放到一块,你要啥我给你组合成啥! 而不是直接就堆到一块! 好了,问题我们说完了,来做素馅吧。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
package top.txiner.bridge;

/**
 * @author : hundred
 * time: 17-12-22
 * website : http://txiner.top
 * 懵懂的小白
 */
public abstract class Vegetable {
    public abstract void change();
}

这个用抽象类吧,接口不像一类食物啊! 先准备好白菜还有茄子

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
package top.txiner.bridge;

/**
 * @author : hundred
 * time: 17-12-22
 * website : http://txiner.top
 * 懵懂的小白
 */
public class Cabbage extends Vegetable {
    @Override
    public void change() {
        System.out.println("I am cabbage");
    }
}
public class Eggplant extends Vegetable {
    @Override
    public void change() {
        System.out.println("I am eggplant");
    }
}

好啦,那我们就得考虑肉馅了! 我们知道,肉馅需要跟素菜分离,只要给它素菜就行了,混合到一块,不管是什么的!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package top.txiner.bridge;

/**
 * @author : hundred
 * time: 17-12-22
 * website : http://txiner.top
 * 懵懂的小白
 */
public abstract class Meat {
    private Vegetable veg;

    public Meat(Vegetable veg){
        this.veg=veg;
    }


    public abstract void taste();


    public void mix(){
        this.veg.change();
        this.taste();
    }
}

买肉去吧。

 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
package top.txiner.bridge;

/**
 * @author : hundred
 * time: 17-12-22
 * website : http://txiner.top
 * 懵懂的小白
 */
public class Pork extends Meat {

    public Pork(Vegetable veg) {
        super(veg);
    }

    @Override
    public void taste() {
        System.out.println("I am pork");
    }
}
public class Beef extends Meat {

    public Beef(Vegetable veg) {
        super(veg);
    }

    @Override
    public void taste() {
        System.out.println("I am beef");
    }
}

买好了做饺子,客户说要什么味道就给混合成什么味道!

1
2
3
4
5
6
7
public class Dumpling {
    public static void main(String[] args) {
        Vegetable cabbage=new Cabbage();
        Meat pork=new Pork(cabbage);
        pork.mix();
    }
}

哈哈,饺子大卖! ------------------------------------分割线------------------------------- 我们看到了,菜跟肉是用Vegatable和Meat抽象联系起来的,没有很强的耦合关系。修改抽象肉的实现牛肉也对包饺子没啥影响。