设计模式-桥接模式

2016-07-28  本文已影响9人  IAmWhoAmI

将抽象部分与它的实现部分分离,使独立。
抽象和抽象直接连起来,然后实现抽象类的其他函数,那么这两个类就连起来了。


abstract class Person{
    private Clothing clothing;
    private String type;

    public Clothing getClothing() {
        return clothing;
    }

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

    public void setType(String type) {
        this.type = type;
    }

    public String getType() {
        return type;
    }
    public abstract void dress();
}
class Man extends Person{
   public Man(){
       setType("man");
   }
    public void dress(){
        Clothing clothing =getClothing();
        clothing.personDressCloth(this);
    }
}
class Lady extends Person{
    public Lady(){
        setType("lady");
    }
    public void dress(){
        Clothing clothing =getClothing();
        clothing.personDressCloth(this);
    }
}
abstract class Clothing{
    public abstract void personDressCloth(Person person);
}

class Jacket extends Clothing{

    @Override
    public void personDressCloth(Person person) {
        System.out.println(person.getType()+"jacket");
    }
}

class Trouser extends Clothing{
    @Override
    public void personDressCloth(Person person) {
        System.out.println(person.getType()+"trouser");
    }
}

public class BridgeTest {
    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);
    }
}
上一篇下一篇

猜你喜欢

热点阅读