Decorator Pattern

Published: 2018-01-08 • Updated: 2019-09-09

Characteristics of Decorator

  • Add behaviour/functionality to an existing object without affecting other object
  • Known as Wrappers
  • Dynamically computes the behaviour of a particular implementation
  • Combination of inheritance and Composition

Examples of Decorator

  • IO Streams

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

  • New Class for every feature
  • Complex because of a large number of objects
  • Complex for clients as it requires large chaining of objects

To access the full working code sample, click here

References

Design Pattern
Share this Post