装饰模式

  • 动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活
  •  
    /**
     * 必须复写父类的无参构造方法,不然如果只有有参的构造方法,子类在继承时,就会复写有参的构造方法,子类再自行创建其他构造方法就会报错。
     */
    public class Person {
        private String name;
        public Person() {
    
        }
        public Person(String name) {
            this.name = name;
        }
    
    
        public void show() {
            System.out.print("装扮的" + name);
        }
    
    }
    
    
    public class Finery extends Person {
    
    
        private Person person;
    
        public void Finery(Person person) {
            this.person = person;
    
        }
    
        @Override
        public void show() {
            if (person != null) {
                person.show();
            }
        }
    }
    
    
    
    
    public class Tshirts extends Finery {
    
    
        @Override
        public void show() {
            System.out.print(" 大T恤");
            super.show();
        }
    }
    
    
    public class BigTrouser extends Finery {
    
    
        @Override
        public void show() {
            System.out.print(" 垮裤");
            super.show();
        }
    }
    
    
    
    public class TestUtil {
    
        public static void main(String[] args) {
          
    
            Person p = new Person("rabbit");
            Tshirts t = new Tshirts();
            BigTrouser bt = new BigTrouser();
    
            bt.Finery(p);
            t.Finery(bt);
            //如果t、bt都同时调用show方法,就会报内存溢出,所以千万要注意。
            t.show();
        }
    }
原文地址:https://www.cnblogs.com/fatRabbit-/p/10170905.html