裝飾模式為對象動態添加職責(穿衣服、穿鞋),但如何實現「脫鞋」(移除裝飾)?
裝飾模式只支持疊加,不支持移除。裝飾鏈構建後為單向鏈表:
ConcreteComponent → DecoratorA → DecoratorB → DecoratorC
無法從中間移除 DecoratorB,因為 DecoratorA 持有 DecoratorB 的引用,且接口不暴露移除操作。
Component c = new DecoratorA(new ConcreteComponent()); // 無 DecoratorB
interface State { void wear(); void remove(); }
class WithShoes implements State { ... }
class WithoutShoes implements State { ... }
class Person {
List decorations = new ArrayList<>();
void add(Decorator d) { decorations.add(d); }
void remove(Decorator d) { decorations.remove(d); }
}