美文网首页
设计模式-装饰者模式

设计模式-装饰者模式

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

    动态增加额外的功能

    
    interface DPerson{
        void eat();
    }
    
    class DMan implements DPerson{
    
        @Override
        public void eat() {
            System.out.println("man eat");
        }
    }
    
    abstract class Decorator implements DPerson{
        protected DPerson person;
    
        public void setPerson(DPerson person) {
            this.person = person;
        }
    
        @Override
        public void eat() {
            person.eat();
        }
    }
    
    class ManDecotatorA extends Decorator{
        @Override
        public void eat() {
            super.eat();
            reEat();
            System.out.println("ManDecotatorA");
        }
        public void reEat(){
            System.out.println("eat one more");
        }
    }
    
    class ManDecotatorB extends Decorator{
        @Override
        public void eat() {
            super.eat();
            System.out.println("---------");
            System.out.println("ManDecotatorB");
        }
        public void reEat(){
            System.out.println("eat one more");
        }
    }
    
    public class DecoratorTest {
        public static void main(String[] args){
            DMan man =new DMan();
            ManDecotatorA a =new ManDecotatorA();
            ManDecotatorB b =new ManDecotatorB();
    
            a.setPerson(man);
            b.setPerson(a);
            b.eat();
    
        }
    }
    

    相关文章

      网友评论

          本文标题:设计模式-装饰者模式

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