The Open-Closed Principle

image.png

Meet the Decorator Pattern

  • Decorators have the same supertype as the objects they decorate.
  • You can use one or more decorators to wrap an object.
  • Given that the decorator has the same supertype as the object it decorates, we can pass around a decorated object in place of the original (wrapped) object.
  • The decorator adds its own behavior before and/or after delegating to the object it decorates to do the rest of the job.

    The Decorator Pattern defined

    The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality
    image.png

    1. public abstract class Beverage {
    2. String description = "Unknown Beverage";
    3. public String getDescription() {
    4. return description;
    5. }
    6. public abstract double cost();
    7. }
    1. public abstract class CondimentDecorator extends Beverage {
    2. Beverage beverage;
    3. public abstract String getDescription();
    4. }

    ```java public class Espresso extends Beverage {

    public Espresso() {

    1. description = "Espresso";

    }

    public double cost() {

    1. return 1.99;

    } }

public class HouseBlend extends Beverage { public HouseBlend() { description = “House Blend Coffee”; }

  1. public double cost() {
  2. return .89;
  3. }

}

  1. ```java
  2. public class Mocha extends CondimentDecorator {
  3. public Mocha(Beverage beverage) {
  4. this.beverage = beverage;
  5. }
  6. public String getDescription() {
  7. return beverage.getDescription() + ", Mocha";
  8. }
  9. public double cost() {
  10. return .20 + beverage.cost();
  11. }
  12. }
  13. public class Soy extends CondimentDecorator {
  14. public Soy(Beverage beverage) {
  15. this.beverage = beverage;
  16. }
  17. public String getDescription() {
  18. return beverage.getDescription() + ", Soy";
  19. }
  20. public double cost() {
  21. return .15 + beverage.cost();
  22. }
  23. }