标签:
定义:动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。
UML图示:
代码示例:以我最爱吃的冰淇淋为例
/**定义冰淇淋抽象类*/
public abstract class Ice {
//描述
????public String desctription = "unkonw";
????//获取描述
????public abstract String getDestription();
????//计费
????public abstract double cost();
????//打印
????public void print(){
????????System.out.println(getDestription() + " / " + cost());
????}
}
?
/**牛奶冰淇淋*/
public class MilkIce extends Ice{
????public MilkIce() {
????????// TODO Auto-generated constructor stub
????????desctription = "milk";
????}
????@Override
????public double cost() {
????????// TODO Auto-generated method stub
????????return 2.0d;
????}
????@Override
????public String getDestription() {
????????// TODO Auto-generated method stub
????????return desctription;
????}
}
?
/**
* 定义冰淇淋装饰者*/
public abstract class IceDecorator extends Ice{
????protected Ice mIce = null;
????public IceDecorator(Ice ice) {
????????// TODO Auto-generated constructor stub
????????mIce = ice;
????}
}
?
/**草莓佐料*/
public class StrawberryDecorator extends IceDecorator{
????public StrawberryDecorator(Ice ice) {
????????super(ice);
????????// TODO Auto-generated constructor stub
????}
????@Override
????public String getDestription() {
????????// TODO Auto-generated method stub
????????return mIce.getDestription() + "Strawberry";
????}
????@Override
????public double cost() {
????????// TODO Auto-generated method stub
????????return mIce.cost() + 0.5d;
????}
}
?
/**巧克力佐料*/
public class ChocolateDecorator extends IceDecorator{
????public ChocolateDecorator(Ice ice) {
????????super(ice);
????????// TODO Auto-generated constructor stub
????}
????@Override
????public String getDestription() {
????????// TODO Auto-generated method stub
????????return mIce.getDestription() + "chocolate";
????}
????@Override
????public double cost() {
????????// TODO Auto-generated method stub
????????return mIce.cost() + 0.8d;
????}
}
?
public class Main {
????public static void main(String[] args) {
????????Ice strawberry_milk = new MilkIce();//定义牛奶草莓冰淇淋
????????Ice chocolate_milk = new MilkIce();//定义牛奶巧克力冰淇淋
????????strawberry_milk = new StrawberryDecorator(strawberry_milk);//加草莓装饰
????????chocolate_milk = new ChocolateDecorator(chocolate_milk);//加巧克力装饰
????????strawberry_milk.getDestription();
????????strawberry_milk.cost();
????????chocolate_milk.getDestription();
????????chocolate_milk.cost();
????????
????????strawberry_milk.print();
????????chocolate_milk.print();
????}
}
打印结果:
milkStrawberry / 2.5
milkchocolate / 2.8
标签:
原文地址:http://www.cnblogs.com/jaden/p/4393630.html