package Decorator_pattern;
/*
* 这里举一个简单的例子:披萨都是由一个抽象的Food然后实例出的原味Pizza来代表和上面可以加辅料如香肠和蔬菜组成,香肠和蔬菜
* 同样属于食物所以可以继承自Food。
*/
abstract class Food {
String description = "我能吃";
public String getDescription() {
return description;
}
public abstract double cost();
}
abstract class Flavour extends Food { // 披萨上的一些辅料作为修饰
public abstract String getDescription();
}
class Pizza extends Food {
public Pizza() {
description = "披萨";
}
@Override
public double cost() {
return 2.6;
}
}
class Sausage extends Flavour {
Food food;
public Sausage(Food food) {
this.food = food;
}
@Override
public String getDescription() {
return "香肠" + this.food.getDescription();
}
@Override
public double cost() {
return this.food.cost() + 1.2;
}
}
class Vegetable extends Flavour {
Food food;
public Vegetable(Food food) {
this.food = food;
}
@Override
public String getDescription() {
return "蔬菜" + this.food.getDescription();
}
@Override
public double cost() {
return this.food.cost() + 1.1;
}
}
// 测试代码
public class Main {
public static void main(String args[]) {
Food food = new Pizza();
System.out.println("初始就是一个原味的披萨");
System.out.println(food.getDescription() + " " + food.cost());
food = new Sausage(food);
System.out.println("加了一份香肠之后");
System.out.println(food.getDescription() + " " + food.cost());
food = new Vegetable(food);
System.out.println("加了一份蔬菜之后");
System.out.println(food.getDescription() + " " + food.cost());
}
}
设计模式——装饰者模式
最新推荐文章于 2024-10-16 23:20:53 发布
414

被折叠的 条评论
为什么被折叠?



