设计模式-结构型之装饰器(decorator)模式

定义
  • 不修改类、接口的情况下增加功能。
  • 将新需求委托给被装饰者去处理 。(当多次被装饰时,就会形成递归结构,功能的递归调用,而composite模式是类关系的一种递归结构)
使用场景
  • 在原有的功能基础上新增功能。
UML图

以蛋糕为例:一块蛋糕,加上奶油,奶油蛋糕,同理,有巧克力蛋糕,巧克力奶油蛋糕,等等。
在这里插入图片描述

代码实现
//蛋糕抽象类:装饰者和被装饰者的父类
public abstract class Cake {
    public abstract String taste();
}
//原始蛋糕:被装饰者
public class PrimitiveCake extends Cake {

    private String type;

    public PrimitiveCake(String type) {
        this.type = type;
    }

    @Override
    public String taste() {
        return this.type + "的味道";
    }
}
//作料抽象类:装饰者
public abstract class Season extends Cake {
    //使用protected;交由子类处理
    protected Cake cake;
    protected Season(Cake cake){
        this.cake = cake;
    }
}
//具体作料类:奶油蛋糕,为蛋糕添加奶油
public class CreamCake extends Season {

    private String type;

    public CreamCake(Cake cake,String type) {
        super(cake);
        this.type = type;
    }

    @Override
    public String taste() {
        return this.type + cake.taste();
    }
}
//具体作料类:巧克力蛋糕,为蛋糕添加巧克力
public class ChocolateCake extends Season {

    private String type;

    public ChocolateCake(Cake cake,String type) {
        super(cake);
        this.type = type;
    }

    @Override
    public String taste() {
        return this.type + cake.taste();
    }
}
//测试
public class Client {
    public static void main(String[] args) {
        ChocolateCake cake = new ChocolateCake(
                new CreamCake(
                        new PrimitiveCake("原始甜"), "奶油"), "巧克力");
        System.out.println(cake.taste());
    }
}
//输出
//巧克力奶油原始甜的味道
总结
  • 不修改类、接口的情况下,在原有的功能基础上新增功能。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值