蘇阿細 - 装饰者模式
type: channel
link: https://www.wangchouchou.com/tag/%E8%A3%85%E9%A5%B0%E8%80%85%E6%A8%A1%E5%BC%8F/
items: 结构型模式-装饰者模式

结构型模式-装饰者模式
type: item
date: 2022-09-05T14:39:00+00:00
description: （1）概述在不改变现有对象结构的情况下，动态的给该对象增加额外的职责或功能（2）结构抽象构建角色：定义一个抽象接口以规范准备接收附加责任的对象具体构建角色：实现抽象构建，通过装饰角色为其添加一些职责抽象装饰角色：继承或实现抽象构建，并包含具体构建的实例，可以通过其子类扩展具体构建的功能具体装饰角色：实现抽象装饰的相关方法，并给具体构建对象添加附加的职责或功能（3）案例以快餐店为例：抽象构建角色public abstract class FastFood { private float price; private String desc; public FastFood() { } public FastFood(float price, String desc) { this.price = price; this.desc = desc; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } /** * 计算价格 * * @return */ public abstract float cost(); }具体构建角色public class FriedNoodles extends FastFood { public FriedNoodles() { super(8, "炒面"); } @Override public float cost() { return super.getPrice(); } } public class FriedRice extends FastFood { public FriedRice() { super(10, "炒饭"); } @Override public float cost() { return super.getPrice(); } }抽象装饰角色public abstract class Garnish extends FastFood { private FastFood fastFood; public Garnish(FastFood fastFood, float price, String desc) { super(price, desc); this.fastFood = fastFood; } public FastFood getFastFood() { return fastFood; } public void setFastFood(FastFood fastFood) { this.fastFood = fastFood; } }具体装饰角色public class Egg extends Garnish { public Egg(FastFood fastFood) { super(fastFood, 1, "鸡蛋"); } @Override public float cost() { //价格：鸡蛋 + 快餐的价格 return super.getPrice() + super.getFastFood().cost(); } @Override public String getDesc() { //描述：鸡蛋 + 具体的快餐 return super.getDesc() + super.getFastFood().getDesc(); } } public class Bacon extends Garnish { public Bacon(FastFood fastFood) { super(fastFood, 2, "培根"); } @Override public float cost() { //价格：培根 + 快餐的价格 return super.getPrice() + super.getFastFood().cost(); } @Override public String getDesc() { //描述：培根 + 具体的快餐 return super.getDesc() + super.getFastFood().getDesc(); } }测试public class Client { public static void main(String[] args) { //炒饭 FastFood food = new FriedRice(); System.out.println(fo…