作用:针对目标方法进行增强,提供新的功能或者额外的功能。
    不同于适配器模式和桥接模式,装饰器模式涉及是单方,和代理模式相同,而且目标必须是抽象的,实际上代理模式和装饰器模式一样,只在目标的存在上有些差距。
    分析:
    1. 涉及的是单方的。
    2. 目标是抽象的
    特点:整个适配器模式中不存在双方调用,要解决的也不是双方调用的问题,而是解决单方提供对外服务的问题,这个单方在自行对外提供服务时,功能不足,或者我们需要额外添加一些新功能,这时就可以使用装饰者模式,单方进行增强。
    解析:
    1. 代理是全权代理,目标根本不对外,全部由代理类来完成
    2. 装饰是增强,是辅助,目标仍可以自行对外提供服务,装饰器只做增强。

    1. /**
    2. * 房子
    3. */
    4. public interface House {
    5. void ourput();
    6. }
    1. /**
    2. * 我的房子
    3. */
    4. public class MyHouse implements House {
    5. @Override
    6. public void ourput() {
    7. System.out.println("这是我的房子");
    8. }
    9. }
    1. /**
    2. * 他的房子
    3. */
    4. public class HeHouse implements House {
    5. @Override
    6. public void ourput() {
    7. System.out.println("这是他的房子");
    8. }
    9. }
    1. /**
    2. * 装饰器
    3. */
    4. public class Decorator implements House {
    5. private House house;
    6. public Decorator(House house) {
    7. this.house = house;
    8. }
    9. @Override
    10. public void ourput() {
    11. System.out.println("针对房子前段装饰");
    12. house.ourput();
    13. System.out.println("针对房子后段装饰");
    14. }
    15. }
    1. public class Clienter {
    2. public static void main(String[] args) {
    3. House myHouse = new MyHouse();
    4. House decorator = new Decorator(myHouse);
    5. decorator.ourput();
    6. }
    7. }

    image.png