美文网首页
设计模式-桥接模式

设计模式-桥接模式

作者: IAmWhoAmI | 来源:发表于2016-07-28 09:50 被阅读9次

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

    
    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);
        }
    }
    

    相关文章

      网友评论

          本文标题:设计模式-桥接模式

          本文链接:https://www.haomeiwen.com/subject/qcaojttx.html