• 周三. 4月 24th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

021.7 装饰设计模式

admin

11月 28, 2021

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

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

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注