装饰则模式

装饰者
概念:动态的为对象增加额外的职责,比生成子类更为灵活。
实例中,Component ConcreteComponent都为Person。

//公共接口,也是目标类,职责的承受者
public interface Person {

   void eat();

}
//装饰者类,负责生成职责
public abstract class Decorator implements Person {

    protected Person person;

    public void setPerson(Person person) {
        this.person = person;
    }

    public void eat() {
        person.eat();
    }
}
//具体职责A
public class ManDecoratorA extends Decorator {

    public void eat() {
        super.eat();
        reEat();
        System.out.println("ManDecoratorA类");
    }

    public void reEat() {
        System.out.println("再吃一顿饭");
    }
}
//具体职责B
 class ManDecoratorB extends Decorator {

    public void eat() {
        super.eat();
        System.out.println("吃成猪");
        System.out.println("ManDecoratorB类");
    }
 }
    //具体职责C
    class ManDecoratorC extends Decorator {

        public void eat() {
            super.eat();
            System.out.println("吃前祈祷");
            System.out.println("ManDecoratorC类");
        }
//调用
public static void main(String[] args) {
        Man man = new Man();
        ManDecoratorC md3 = new ManDecoratorC();
        ManDecoratorA md1 = new ManDecoratorA();
        ManDecoratorB md2 = new ManDecoratorB();
        //先设置父类中 Person 的具体实现 ,在执行eat方法时。  super.eat();都是先执行父类的eat(),也就是
        //具体传入的实现,

        /**
         * 执行第一条前,父类中 Person为Man,父类执行的eat()就是Man的eat()
         */
        md3.setPerson(man);
        /**
         * 执行第二条前,父类中 Person为Man3,父类执行的eat()就是Man3的eat()
         */
        md1.setPerson(md3);
        /**
         * 执行第三条前,父类中 Person为Man1,父类执行的eat()就是Man1的eat()
         */
        md2.setPerson(md1);
        /**
         * 执行第四条前,先执行父类的eat(),在执行本类。md2的父类eat()为eat1(),md1的父类eat()为eat3(),
         * ,md3的父类eat()为具体实现的eat()
         */
        md2.eat();

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值