Creating and Extending Objects with the Decorator Patterns : Decorator Pattern « Design Pattern « Java Tutorial






public class MainClass {
  public static void main(String args[]) {
    Computer computer = new Computer();

    computer = new Disk(computer);
    computer = new Monitor(computer);
    computer = new CD(computer);
    computer = new CD(computer);

    System.out.println("You're getting a " + computer.description() + ".");
  }
}

class Disk extends ComponentDecorator {
  Computer computer;

  public Disk(Computer c) {
    computer = c;
  }

  public String description() {
    return computer.description() + " and a disk";
  }
}

class CD extends ComponentDecorator {
  Computer computer;

  public CD(Computer c) {
    computer = c;
  }

  public String description() {
    return computer.description() + " and a CD";
  }
}

class Computer {
  public Computer() {
  }

  public String description() {
    return "computer";
  }
}

abstract class ComponentDecorator extends Computer {
  public abstract String description();
}

class Monitor extends ComponentDecorator {
  Computer computer;

  public Monitor(Computer c) {
    computer = c;
  }

  public String description() {
    return computer.description() + " and a monitor";
  }
}








34.10.Decorator Pattern
34.10.1.Coffee example using decorators
34.10.2.combinations and decorators
34.10.3.Creating and Extending Objects with the Decorator Patterns