裝飾者模式:動態地將責任附加到對象上。想要擴展功能,裝飾者提供有別於繼承的另外一種選擇。java
裝飾者模式UML圖:ide
裝飾者模式具體例子:this
public abstract class Beverage { String desription = "Unknown Beverage"; public String getDescription(){ return desription; } public abstract double cost(); }
public abstract class CondimentDecorator extends Beverage{ public abstract String getDescription(); }
public class DarkRoast extends Beverage { public DarkRoast(){ desription = "Dark Roast Coffee"; } @Override public double cost() { // TODO Auto-generated method stub return 2.10; } }
public class Espresso extends Beverage { public Espresso(){ desription = "Espresso"; } @Override public double cost() { // TODO Auto-generated method stub return 1.99; } }
public class HouseBlend extends Beverage { public HouseBlend(){ desription = "HouseBlend"; } @Override public double cost() { // TODO Auto-generated method stub return .89; } }
public class Mocha extends CondimentDecorator { Beverage beverage; public Mocha(Beverage beverage){ this.beverage = beverage; } @Override public String getDescription() { // TODO Auto-generated method stub return beverage.getDescription()+", Mocha"; } @Override public double cost() { // TODO Auto-generated method stub return .20 + beverage.cost(); } }
public class Soy extends CondimentDecorator { Beverage beverage; public Soy(Beverage beverage){ this.beverage = beverage; } public int getSize(){ return beverage.getSize(); } @Override public String getDescription() { // TODO Auto-generated method stub return beverage.getDescription()+", Soy"; } @Override public double cost() { // TODO Auto-generated method stub return .10 + beverage.cost(); } }
使用場景:java.io類code