1.装饰器模式介绍
- 意图:动态的给一个对象添加一些额外的责任,装饰器模式相比生成子类更加灵活
- 使用场景:给一个类动态增加功能和动态撤销功能,提高灵活性,而不修改原有的类
- 优点:装饰类和被装饰类可以独立发展,不会互相耦合,装饰模式是继承的一个替代模式
- 缺点:多层装饰比较复杂
2.代码实现之
interface Action{
void sleep();
}
public class Sleep implements Action {
@Override
public void sleep() {
System.out.println("睡觉...");
}
}
class SleepBeforeDecorator implements Action{
Action action;
public SleepBeforeDecorator(Action action) {
this.action = action;
}
@Override
public void sleep() {
System.out.println("睡觉前自动打开空调...");
action.sleep();
}
}
class SleepAfterDecorator implements Action{
Action action;
public SleepAfterDecorator(Action action) {
this.action = action;
}
@Override
public void sleep() {
action.sleep();
System.out.println("睡着后自动关灯....");
}
}
class Test{
public static void main(String[] args) {
Action beforeAction = new SleepBeforeDecorator(new Sleep());
beforeAction.sleep();
System.out.println("====================");
Action afterAction = new SleepAfterDecorator(new Sleep());
afterAction.sleep();
System.out.println("=====================");
Action beforeAfterAction = new SleepBeforeDecorator(afterAction);
beforeAfterAction.sleep();
}
}
睡觉前自动打开空调...
睡觉...
====================
睡觉...
睡着后自动关灯....
=====================
睡觉前自动打开空调...
睡觉...
睡着后自动关灯....