Decorator Pattern

Characteristics of Decorator

Examples of Decorator

Java Implementaion

Phone.class

public interface Phone {
  String build();
}

SmartPhone.class

/*
To decorate Phone we need to create an Abstract implementation
Which acts as decorator
 */
public abstract class SmartPhone implements Phone {

  private Phone phone;

  public SmartPhone(Phone phone) {
    this.phone = phone;
  }

  @Override
  public String build(){
    return phone.build();
  }
}

AndroidPhone.class

/*
Decorator Implementation
 */
public class AndroidPhone extends SmartPhone {

  public AndroidPhone(Phone phone) {
    super(phone);
  }

  /*
  Adding new functionality to existing implementation
   */
  @Override
  public String build(){
    return super.build() + addOS();
  }

  private String addOS() {
    return " + Android OS v8.0";
  }
}

Disadvantages of Decorator

To access the full working code sample, click here

References

Decorator Design Pattern | Implementation and Disadvantages | Clean Code Series

SUBSCRIBE TO NEW CONTENT

Tutorials on System Design, BlockChain, Design Patterns and more sent out once a week.

Loading comments...