lundi 25 avril 2022

What are the main reasons for using an interface in the decorator design pattern?

interface Dress {
  public void assemble();
}

class BasicDress implements Dress {
  @Override public void assemble() {
    System.out.println("Basic Dress Features");
  }
}

class DressDecorator implements Dress {
  protected Dress dress;

  public DressDecorator(Dress c) {
    this.dress = c;
  }

  @Override public void assemble() {
    this.dress.assemble();
  }
}

class SportyDress extends DressDecorator {
  public SportyDress(Dress c) {
    super(c);
  }
  
  @Override public void assemble() {
    super.assemble();
    System.out.println("Adding Sporty Dress Features");
  }
}

class FancyDress extends DressDecorator {
  public FancyDress(Dress c) {
    super(c);
  }
  
  @Override
  public void assemble() {
    super.assemble();
    System.out.println("Adding Fancy Dress Features");
  }
}

public class DecoratorPatternTest {
  public static void main(String[] args) {
    Dress sportyDress = new SportyDress(new BasicDress());
    sportyDress.assemble();
    System.out.println();
    
    Dress fancyDress = new FancyDress(new BasicDress());
    fancyDress.assemble();
    System.out.println();  
  }
}

Why do we need an interface in the decorator design pattern?

Aucun commentaire:

Enregistrer un commentaire