021.7 装饰设计模式


解决问题 :给对象提供额外的功能(职责),比继承更灵活

public class PersonDemo
{

    public static void main(String[] args)
    {
        Person p = new Person();
        NewPerson np = new NewPerson(p);
        np.eat();
    }
}

class Person{
    void eat(){
        System.out.println("eat");
    }
}

//装饰器
class NewPerson{
    private Person p;
    public NewPerson(Person p){
        this.p = p;
    }
    void eat(){
        System.out.println("开胃");
        p.eat();
        System.out.println("甜点");
    }
}

//继承
class SubPerson extends Person{
    void eat(){
        System.out.println("开胃");
        super.eat();
        System.out.println("甜点");
    }
}

 

posted @ 2018-05-07 19:23  Alos403  阅读(170)  评论(0编辑  收藏  举报