看到字眼,你应该心里有个数了,所谓装饰,就是在原有的基础上加些东西化化装,有修睫毛的,有化口红的,有时尚的衣服等等,然后呢就 变漂亮了;比如礼品,都要加个礼品
盒,然后档次提高了,可以开个好价 ,这也是“装饰”。
装饰者模式有个 需要遵循的原则:开闭原则,即对修改关闭,对扩展开放。
什么情况下需要用到装饰装者模式? 我的理解就是:当我已经提供了一些method,而你要使用我的method,那么你只能在不损坏我的method 的前提下,在我的method的基础
上 进行扩展,也就是覆盖处理。
使用装饰者模式有什么好处? 就是不损坏需要装饰的类,也即保护需要装饰的类。
实例代码:
beverage.java
[java]
public abstract class Beverage{
String description="Unknown Beverage";
String size="medium";
public String getDescription(){
return description;
}
public abstract double cost();
public String getSize(){
return size;
}
public void setSize(String size_){
this.size=size_;
}
}
CondimentDecorator.java
[java]
public abstract class CondimentDecorator extends Beverage{
public abstract String getDescription();
}
Espresso.java
[java]
public class Espresso extends Beverage{
public Espresso(){
description="Espresso";
}
public double cost(){
return 1.99;
}
}
HouseBlend.java
[java]
public class HouseBlend extends Beverage{
public HouseBlend(){
description="HouseBlend";
}
public double cost(){
return 0.89;
}
}
DarkRoast.java
[java]
public class DarkRoast extends Beverage{
public DarkRoast(){
description="DarkRoast";
}
public double cost(){
return 0.99;
}
}
Mocha.java
[java]
public class Mocha extends CondimentDecorator{
Beverage beverage;
public Mocha(Beverage beverage){
this.beverage=beverage;
}
public String getDescription(){
return beverage.getDescription()+",Mocha";
}
public double cost(){
return 0.2+beverage.cost();
}
}
Soy.java
[java]
public class Soy extends CondimentDecorator{
Beverage beverage;
public Soy(Beverage beverage){
this.beverage=beverage;
}
public String getDescription(){
return beverage.getDescription()+",Soy";
}
public double cost(){
return 0.15+beverage.cost();
}
}
Whip.java
[java]
public class Whip extends CondimentDecorator{
Beverage beverage;
public Whip(Beverage beverage){
this.beverage=beverage;
}
public String getDescription(){
return beverage.getDescription()+",Whip";
}
public double cost(){
return 0.10+beverage.cost();
}
}
BeverageSize.java
[java]
public class BeverageSize extends CondimentDecorator{
public double size=0;
public Beverage beverage;
public BeverageSize(Beverage beverage){
this.beverage=beverage;
}
public String getDescription(){
return beverage.getDescription()+","+beverage.getSize();
}
public double cost(){
switch(beverage.getSize()){
case "small":
return 0.10+beverage.cost();
case "medium":
return 0.15+beverage.cost();
case "big":
return 0.20+beverage.cost();
default:
return 0.15+beverage.cost();