首先根据3要素来创建需要创建的类:(根据要素这种方便记忆)

1通用接口 2装饰器类实现通用接口3新增类继承装饰器类扩展功能


1定义一个通用接口Phone

/**
 * 首先定义一个通用接口
 *
 * @author czh
 * @date 2023/5/16
 */
public interface Phone {
    /**
     * 手机都有接打电话功能
     */
    void answerThePhone();
}

2两个Phone实现类

apple

@Slf4j
@Component
public class ApplePhone implements Phone {
    @Override
    public void answerThePhone() {
      log.info("苹果手机实现接打电话功能");
    }
}

huawei

@Slf4j
@Component

public class HuaWeiPhone implements Phone {
    @Override
    public void answerThePhone() {
      log.info("华为手机实现接打电话功能");
    }
}

3定义一个装饰器类实现通用Phone接口

public class Ornament implements Phone {
    protected Phone phone;

    public Ornament(Phone phone1) {
        this.phone = phone1;
    }

    @Override
    public void answerThePhone() {
        phone.answerThePhone();
    }

}

4定义装饰器实现类,在里面扩展功能

@Slf4j
public class OrnamentService extends Ornament {
    public OrnamentService(Phone phone1) {
        super(phone1);
        wirelessCharging();
    }
    private void wirelessCharging(){
        log.info("扩展无线充电功能");
    }
}

5调用

@RequestMapping("/ornament")
@RestController
public class OrnamentController {

    @Autowired
    ApplePhone applePhone;

    @GetMapping("/test")
    public void test() {
        Ornament ornament = new OrnamentService(applePhone);
        ornament.answerThePhone();
    }
}