跳转到内容
主菜单
主菜单
移至侧栏
隐藏
导航
首页
最近更改
随机页面
MediaWiki帮助
代码酷
搜索
搜索
中文(中国大陆)
外观
创建账号
登录
个人工具
创建账号
登录
未登录编辑者的页面
了解详情
贡献
讨论
编辑“︁
Java装饰模式
”︁(章节)
页面
讨论
大陆简体
阅读
编辑
编辑源代码
查看历史
工具
工具
移至侧栏
隐藏
操作
阅读
编辑
编辑源代码
查看历史
常规
链入页面
相关更改
特殊页面
页面信息
外观
移至侧栏
隐藏
您的更改会在有权核准的用户核准后向读者展示。
警告:
您没有登录。如果您进行任何编辑,您的IP地址会公开展示。如果您
登录
或
创建账号
,您的编辑会以您的用户名署名,此外还有其他益处。
反垃圾检查。
不要
加入这个!
== 代码示例 == 以下是一个模拟咖啡订单系统的示例,展示如何通过装饰模式动态添加配料(如牛奶、糖)的价格和描述。 === 基础组件 === <syntaxhighlight lang="java"> // 抽象组件 public interface Coffee { double getCost(); String getDescription(); } // 具体组件 public class SimpleCoffee implements Coffee { @Override public double getCost() { return 2.0; // 基础咖啡价格 } @Override public String getDescription() { return "Simple coffee"; } } </syntaxhighlight> === 装饰器实现 === <syntaxhighlight lang="java"> // 抽象装饰器 public abstract class CoffeeDecorator implements Coffee { protected Coffee decoratedCoffee; public CoffeeDecorator(Coffee coffee) { this.decoratedCoffee = coffee; } @Override public double getCost() { return decoratedCoffee.getCost(); } @Override public String getDescription() { return decoratedCoffee.getDescription(); } } // 具体装饰器:牛奶 public class MilkDecorator extends CoffeeDecorator { public MilkDecorator(Coffee coffee) { super(coffee); } @Override public double getCost() { return super.getCost() + 0.5; // 增加牛奶价格 } @Override public String getDescription() { return super.getDescription() + ", with milk"; } } // 具体装饰器:糖 public class SugarDecorator extends CoffeeDecorator { public SugarDecorator(Coffee coffee) { super(coffee); } @Override public double getCost() { return super.getCost() + 0.2; // 增加糖价格 } @Override public String getDescription() { return super.getDescription() + ", with sugar"; } } </syntaxhighlight> === 使用示例 === <syntaxhighlight lang="java"> public class Main { public static void main(String[] args) { Coffee coffee = new SimpleCoffee(); System.out.println("Cost: " + coffee.getCost() + "; Description: " + coffee.getDescription()); coffee = new MilkDecorator(coffee); System.out.println("Cost: " + coffee.getCost() + "; Description: " + coffee.getDescription()); coffee = new SugarDecorator(coffee); System.out.println("Cost: " + coffee.getCost() + "; Description: " + coffee.getDescription()); } } </syntaxhighlight> '''输出''': <pre> Cost: 2.0; Description: Simple coffee Cost: 2.5; Description: Simple coffee, with milk Cost: 2.7; Description: Simple coffee, with milk, with sugar </pre>
摘要:
请注意,所有对代码酷的贡献均被视为依照知识共享署名-非商业性使用-相同方式共享发表(详情请见
代码酷:著作权
)。如果您不希望您的文字作品被随意编辑和分发传播,请不要在此提交。
您同时也向我们承诺,您提交的内容为您自己所创作,或是复制自公共领域或类似自由来源。
未经许可,请勿提交受著作权保护的作品!
取消
编辑帮助
(在新窗口中打开)