September 30, 2011

Decorator Design Pattern code example in Java

Abstract Type


public interface IEmail {
   public String getContents();
}

Concrete Type

public class Email implements IEmail {
   private String content;
   public Email(String content) {
      this.content = content;
   }

   @Override
   public String getContents() {
      //general email stuff
      return content;
   }
}

Abstract Type Decorator

public abstract class EmailDecorator implements IEmail {
  
   //wrapped component
   IEmail originalEmail;

   public IEmail getOriginalEmail() {
      return this.originalEmail;
   }

   public void setOriginalEmail(IEmail email) {
      this.originalEmail = email;
   }
}

Concrete Type Decorator

public class SecureEmailDecorator extends EmailDecorator {

   private String content;
   public SecureEmailDecorator(IEmail basicEmail) {
      setOriginalEmail(basicEmail);
   }

   @Override
   public String getContents() {
      //  secure original
      content = encrypt(getOriginalEmail().getContents());
      return content;
   }

   private String encrypt(String message) {
      //encrypt the string
      return  encryptedMessage;
   }
}

Client

public class EmailSender {

   public void sendEmail(IEmail email) {
      // get hold of email contents
      email.getContents();

      // send email code here
   }

   public static void main(String[] args) {
      EmailSender emailSender = new EmailSender();

      IEmail email = new Email();

      // Sending normal email
      emailSender.sendEmail(email);

      // Sending Secure email
      emailSender.sendEmail(new SecureEmailDecorator(email));
   }
}

1 comment:

  1. Great post and thanks for code. What is most important point with decorator is that it affect only individual object and not all object which itself a big control and flexibility inheritance doesn't offer. See here for another example of decorator pattern in Java.

    ReplyDelete