Featured Post

Event Sourcing Video from Michael Ploed

Event Sourcing I want to share a great video I found few days ago that describes very well what Event Sourcing is.

Saturday, December 28, 2013

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) {
  this.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) {
  this.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.

No comments :

Post a Comment