代码改变世界

android开发 装饰者模式

2016-03-17 11:59  宁小哥  阅读(294)  评论(0编辑  收藏  举报

1.

package test;

interface Dongwu {
    void eat();
}

2.

package test;

public class Gou implements Dongwu{
    public void eat() {
        // TODO Auto-generated method stub
        System.out.println("我是小狗");
    }

}

3.

package test;

public class Mao implements Dongwu{

    @Override
    public void eat() {
        // TODO Auto-generated method stub
        System.out.println("我是小猫");
    }
    
}

4.

package test;

public class ADongwu implements Dongwu{
    private Dongwu dongwu;
    public ADongwu(Dongwu dongwu) {
        // TODO Auto-generated constructor stub
        this.dongwu = dongwu;
    }
    @Override
    public void eat() {
        // TODO Auto-generated method stub
        System.out.println("A家的动物吃饭前要先跑一跑");
        dongwu.eat();
    }
    
}


5.

package test;

public class BDongwu implements Dongwu{
    private Dongwu dongwu;
    public BDongwu(Dongwu dongwu) {
        // TODO Auto-generated constructor stub
        this.dongwu = dongwu;
    }
    @Override
    public void eat() {
        // TODO Auto-generated method stub
        System.out.println("B家的动物吃饭先要先跳一跳");
        dongwu.eat();
    }

}


6.

package test;

public class Test {
    public static void main(String args []) {
        Gou gou = new Gou();
        ADongwu a = new ADongwu(gou);
        a.eat();
        
        Gou gou2 = new Gou();
        BDongwu b = new BDongwu(gou2);
        b.eat();
    }
}