设计模式(十):装饰者模式

1. 装饰者模式的介绍

装饰器模式(Decorator Pattern)属于结构型模式,允许向一个现有的对象添加新的功能,同时又不改变其结构。

装饰器模式通过将对象包装在装饰器类中,以便动态地修改其行为。

装饰器模式包含四个核心角色:

  • 抽象组件(Component):定义了原始对象和装饰器对象的公共接口或抽象类,可以是具体组件类的父类或接口。
  • 具体组件(Concrete Component):是被装饰的原始对象,它定义了需要添加新功能的对象。
  • 抽象装饰器(Decorator):继承自抽象组件,它包含了一个抽象组件对象,同时可以通过组合方式持有其他装饰器对象。
  • 具体装饰器(Concrete Decorator):实现了抽象装饰器的接口,负责向抽象组件添加新的功能。具体装饰器通常会在调用原始对象的方法之前或之后执行自己的操作。

2. 装饰者模式的类图

在这里插入图片描述

3. 装饰者模式的实现

3.1 创建一个抽象组建Chef

package blog;

/**
 * 厨师
 */
public interface Chef {
    void cook();
}

3.2 创建两个具体组件ChineseChef和EuropeanChef

package blog;

/**
 * 中国厨师
 */
public class ChineseChef implements Chef {

    @Override
    public void cook() {
        System.out.println("制作中餐");
    }
}
package blog;

/**
 * 西方厨师
 */
public class EuropeanChef implements Chef{
    @Override
    public void cook() {
        System.out.println("制作西餐");
    }
}

3.3 创建抽象装饰器ChefDecorator

package blog;

/**
 * 厨师装饰器
 */
public abstract class ChefDecorator implements Chef {
    protected Chef chef;

    public ChefDecorator(Chef chef) {
        this.chef = chef;
    }
}

3.4 创建具体装饰器PlateChefDecorator

package blog;

/**
 * 厨师摆盘装饰器
 */
public class PlateChefDecorator extends ChefDecorator{
    public PlateChefDecorator(Chef chef) {
        super(chef);
    }

    @Override
    public void cook() {
        chef.cook();
        plate();
    }

    private void plate() {
        if (chef instanceof ChineseChef) {
            System.out.println("中式摆盘");
        } else {
            System.out.println("西式摆盘");
        }
    }
}

3.5 测试

package blog;

public class DecoratorDemo {
    public static void main(String[] args) {
        ChineseChef chineseChef = new ChineseChef();
        PlateChefDecorator plateChineseChef = new PlateChefDecorator(chineseChef);
        plateChineseChef.cook();

        EuropeanChef europeanChef = new EuropeanChef();
        PlateChefDecorator plateEuropeanChef = new PlateChefDecorator(europeanChef);
        plateEuropeanChef.cook();

    }
}
  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值