Suggested Pages

Saturday, December 28, 2013

Decorator vs Strategy in a brief description

In this post I will share a good definition found on the WEB about the difference between the Strategy and Decorator Design Patterns.
As the name suggests the Strategy design pattern is dedicated to providing a strategy to the Client while the Decorator design pattern is dedicated to providing an enrichment of a certain functionality.

To be precise the two patterns respond differently to the following question:

Does the functionality need to be swapped or to be added?

  • The design patter Strategy is used to swap different (very different) strategy most of the times.
  • The design patter Decorator is used to add different behaviour (no necessary very different most of the times).

Motivations for the Design-Pattern Decorator

In this post I'm going to explain the motivations of the usage of the design patterns Decorator.
Many developers think that, the easy and common way to perform a new behaviour is the usage of a subclass, but this way of designing the software leads to a complex hierarchical model.
Imagine a requirement that says: "A manager has a different mail signature from the members of his team, He has an additional field : Telephone Number; the manager needs to send his telephone number in the mail.".

A common strategy may be to extend the actual object that composes the mail signature and add the new field phoneNumber.


public class MailSignature {

 private String name;
 private String surname;
 private String company;
        /*NEW FIELD*/
 private String phoneNum;

 public String getName() {
  return name;

 public void setName(String name) { = name;

 public String getSurname() {
  return surname;

 public void setSurname(String surname) {
  this.surname = surname;

 public String getCompany() {
  return company;

 public void setCompany(String company) { = company;

 public String getPhoneNum() {
  return phoneNum;

 public void setPhoneNum(String phoneNum) {
  this.phoneNum = phoneNum;


But let's consider a new requirement: "not all managers have a telephone number".
This implies that we have to consider different combinations over the attributes of the MailSignature object. Therefore a possible solutions can be a sort of Factory that creates the object MailSignature and valorizes it differently for the member of a team and for the manager. This is a "compile time" solution because all the possible combinations you need are planned and written in the Factory .

The described solution achieves the requirement but not in the best way. You should consider instead the Decorator design pattern that suggests you to identify a "Core Mail Signature" and to think to the possible enrichments as phoneNumber, city. In the next post I will describe the Design Pattern Decorator in details.

Suggested Pages