桥梁模式跟上一章介绍的策略模式比较相似
最大的区别就是原始类是一个抽象类,我们可以这样理解
桥梁模式主要是把行为与属性分离。而策略模式只是一个简单的行为模式。所以通过以下的例子可以很好的看出差异:
1、原始类A
public abstract class Human {
private WorkBehavior workBehavior;
protected abstract void appearance();
public void work(){
workBehavior.work();
}
public void setWorkBehavior(WorkBehavior workBehavior) {
this.workBehavior = workBehavior;
}
}
原始类变为抽象类同时增加appearance方法。
2、继承原始类A的抽象类B
public class Guy extends Human{
@Override
protected void appearance() {
System.out.println("He is very handsome");
}
}
3、继承原始类A的抽象类C
public class Beauty extends Human{
@Override
protected void appearance() {
System.out.println("She is very beautiful");
}
}
其他的行为类参考
策略模式
最后的测试类
public class Main {
public static void main(String[] args) {
Human beauty = new Beauty();
beauty.appearance();
beauty.setWorkBehavior(new MarketBehavior());
beauty.work();
beauty.setWorkBehavior(new CodeBehavior());
beauty.work();
Human guy = new Guy();
guy.appearance();
guy.setWorkBehavior(new MarketBehavior());
guy.work();
guy.setWorkBehavior(new CodeBehavior());
guy.work();
}
}
这样属性跟行为就分离了,不管美女还是帅哥都可以从事任何的工作