版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/qq_23934475/article/details/82985417
设计模式之装饰模式(Decorator)
场景
普通人跑步,跳高,举重很普通。
现在需要使用装备变成钢铁侠,3项指标成倍扩大
Man接口
public interface Man {
void run();
int highJump();
int weightlifting();
}
normal man
public class NormalMan implements Man {
@Override
public void run() {
System.out.println("Normal man run.");
}
@Override
public int highJump() {
System.out.println("Normal man heigh jump 1m.");
return 1;
}
@Override
public int weightlifting() {
System.out.println("Normal man weightlifting 30KG.");
return 30;
}
}
iron man
public class IronMan implements Man {
private Man normalMan;
public IronMan(Man normalMan) {
this.normalMan = normalMan;
}
@Override
public void run() {
normalMan.run();
System.out.println("upgrade iron man speed 1000m/s");
}
@Override
public int highJump() {
System.out.println("upgrade iron man highJump "+normalMan.highJump()*100+"m.");
return normalMan.highJump()*100;
}
@Override
public int weightlifting() {
System.out.println("upgrade iron man weightlifting "+normalMan.weightlifting()*100+" KG");
return normalMan.weightlifting()*100;
}
}
测试
@Test
public void decorator(){
Man normalMan = new NormalMan();
normalMan.run();
normalMan.highJump();
normalMan.weightlifting();
System.out.println("==============");
Man ironMan = new IronMan(normalMan);
ironMan.run();
ironMan.highJump();
ironMan.weightlifting();
}
类图
适用性
- 动态且透明地向各个对象添加职责,即不影响其他对象
- 对于可以撤回的责任
- 通过子类扩展是不切实际的。有时可能会有大量独立扩展,并会产生大量子类以支持每种组合。或者类定义可能隐藏或不可用于子类化