在不修改原類別、不使用繼承的前提下,動態為物件新增職責。裝飾類持有被裝飾物件引用,轉發原有操作並插入新行為。
// Component
interface Chifan { void chifan(); }
// ConcreteComponent
class SimpleMeal implements Chifan {
public void chifan() { System.out.println("早餐"); }
}
// Decorator 基類(可選,簡化版直接寫具體裝飾類)
class SuperChifan implements Chifan {
private Chifan target;
public SuperChifan(Chifan target) { this.target = target; }
public void chifan() {
target.chifan(); // 原功能
System.out.println("打牌"); // 新增功能
System.out.println("喝酒");
System.out.println("寫作業");
System.out.println("工作");
}
}
// Client
public class DecoratorDemo {
public static void main(String[] args) {
Chifan meal = new SimpleMeal();
Chifan superMeal = new SuperChifan(meal);
superMeal.chifan();
}
}
早餐
打牌
喝酒
寫作業
工作