(设计模式)桥模式

将抽象接口部分与实现部分分离,使他们可以独立变化。
抽象和实现之间不需要有一个固定绑定关系,在运行时动态切换。
对一个抽象的实现部分修改应对客户不产生影响,即客户的代码不必重新编译。
这一次从主方法看起
public static void main(String[] args) {
    Person man = new Man();
    Person lady = new Lady();
    Clothing jacket = new Jacket();
    Clothing  trouser = new Trouser();
  /*  jacket.personDressCloth(man);
    trouser.personDressCloth(man);
    jacket.personDressCloth(lady);
    trouser.personDressCloth(lady);*/
  man.setClothing(new Jacket());
  man.dress();
  man.setClothing( person -> System.out.println(person.getType()+"穿"));
  man.dress();
}
最后用了java8的表达式,这样可能会比较突出这个模式的特性。可以定义一个只有一个方法的接口 ,然后就可以使用表达式,而真正的实现方法则在使用的时候动态写入执行。
Person接口,传入不同的实现,调用dress 业务方法遍执行相对应的实现。
 
实现类的接口
public interface Clothing {
    public abstract void personDressCloth(Person person);
}
Person 接口
public abstract class Person {
    private Clothing clothing;
    private String type;

    public abstract void dress();

    public Clothing getClothing() {
        return clothing;
    }

    public void setClothing(Clothing clothing) {
        this.clothing = clothing;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}
这里有一个特别的地方,也是这个设计模式的核心。这里有个字段Clothing,这是上面说到的,实现类的接口,这是核心,dress方法是这个接口的业务方法,客户要调用的就是这个方法。接下来看下实现类
 
public class Man extends Person {

    public Man() {
        setType("男人");
    }

    @Override
    public void dress() {
        Clothing clothing = getClothing();
        clothing.personDressCloth(this);
    }
}
dress 方法并不实现业务逻辑,他只负责委托调用接口里的Clothing 字段里的接口方法。通过这样的方式来建立接口和实现的联系和独立。
只要传入不同的Clothing 实现,这样调用dress 业务方法就有不同的实现了。
这就是桥模式,接口的业务方法并不真正实现,而是扮演桥的任务,建立这个接口被调用时应该去联系哪个真正的业务方法,实现业务和接口的分离,动态改变。