装饰者模式的引入

一、装饰者模式

在不使用的继承的方式下,采用装饰设计模式可以扩展一个对象的功能,可以使一个对象变得越来越强大。
装饰者模式模式:用来动态的拓展对象的功能,是继承关系的一种替代方案之一。

    // 普通的写法:new一个对象,然后调用对象的方法
    // TeacherEat teacherEat = new TeacherEat();
    // teacherEat.eat();

    // 装饰者模式,一般是把类对象作为构造参数传递。
    PersonEat personEat = new PersonEat();
    TeacherEat teacherEat = new TeacherEat(personEat);
    teacherEat.eat();

二、继承的方式

public interface Eat {
    void eat();
}
public class PersonEat implements Eat {
    @Override
    public void eat() {
        Log.d("TAG", "人吃饭吃菜略略略");
    }
}

public class StudentEat implements Eat {
    @Override
    public void eat() {
        Log.d("TAG", "雪山个。吃饭吃菜略略略");
    }
}
public class TeacherEat implements Eat {
    @Override
    public void eat() {
        Log.d("TAG", "喝汤");
        Log.d("TAG", "雪山个。吃饭吃菜略略略");
        Log.d("TAG", "不要送盘子");
    }
}

三、装饰者模式

public interface Eat {
    void eat();
}
public class PersonEat implements Eat {
    @Override
    public void eat() {
        Log.d("TAG", "人吃饭吃菜略略略");
    }
}

public class StudentEat implements Eat {
    private Eat eat;
    public StudentEat(PersonEat eat) {
        this.eat = eat;
    }
    @Override
    public void eat() {
        Log.d("TAG", "饭前活动");
        eat.eat();
        Log.d("TAG", "Fan后活动");
    }
}
public class TeacherEat implements Eat {
    private Eat eat;
    public TeacherEat(PersonEat eat) {
        this.eat = eat;
    }
    @Override
    public void eat() {
        Log.d("TAG", "喝汤");
        Log.d("TAG", "雪山个。吃饭吃菜略略略");
        eat.eat(); // 调用Eat对象的eat方法。
        Log.d("TAG", "不要送盘子");
    }
}

你可能感兴趣的:(装饰者模式的引入)