首页 > 其他 > 详细

021.7 装饰设计模式

时间:2018-05-07 20:15:26      阅读:170      评论:0      收藏:0      [点我收藏+]


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

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("甜点");
    }
}

 

021.7 装饰设计模式

原文:https://www.cnblogs.com/-nbloser/p/9004533.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!