装饰者模式

Intent

  • Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
  • Client-specified embellishment of a core object by recursively wrapping it.
  • Wrapping a gift, putting it in a box, and wrapping the box.

Structure

装饰者模式_第1张图片
Structure

实例Demo

  1. 问题描述: 咖啡,有HouseBlend和DarkRoast两种,可以添加Mocha和Soy,计算价格;
  2. 结构图:


    装饰者模式_第2张图片
    Decorator by keith
  3. 实现代码:
public class Decorator {
    public static void main(String[] args) {
        Beverage beverage=new HouseBlend();
        System.out.println(beverage.getDescription()+"  $"+beverage.cost());
        beverage=new Mocha(beverage);
        System.out.println(beverage.getDescription()+"  $"+beverage.cost());
        beverage=new Soy(beverage);
        System.out.println(beverage.getDescription()+"  $"+beverage.cost());
    }
}
abstract class Beverage {
    String description = "Unknown Beverage";

    public String getDescription() {
        return description;
    }

    // calculate the cost of the beverage
    public abstract double cost();
}
class HouseBlend extends Beverage {

    public HouseBlend() {
        description = getClass().getSimpleName();
    }

    @Override
    public double cost() {
        return 1.99;
    }
}
class DarkRoast extends Beverage {

    public DarkRoast() {
        description = getClass().getSimpleName();
    }

    @Override
    public double cost() {
        return 0.89;
    }
}
//base decorator class
abstract class CondimentDecorator extends Beverage {
    Beverage beverage;

    public CondimentDecorator(Beverage beverage) {
        this.beverage = beverage;
    }

    public abstract String getDescription();
}
class Mocha extends CondimentDecorator {

    public Mocha(Beverage beverage) {
        super(beverage);
    }

    @Override
    public String getDescription() {
        return beverage.getDescription() + "," + getClass().getSimpleName();
    }

    @Override
    public double cost() {
        return 0.2 + beverage.cost();
    }
}
class Soy extends CondimentDecorator {

    public Soy(Beverage beverage) {
        super(beverage);
    }

    @Override
    public String getDescription() {
        return beverage.getDescription() + "," + getClass().getSimpleName();
    }

    @Override
    public double cost() {
        return 0.1 + beverage.cost();
    }
}

Notice:

  • 装饰类和组件是同一种类型,并扩展了而外的功能
  • Java I/O中的BufferedInputStream,FilterInputStream等也用到了装饰者模式

Reference:

  1. Design Patterns

你可能感兴趣的:(装饰者模式)