Pages

Saturday, October 5, 2013

Can you please wrap the gift? It is for my grandma.

Have you ever been in the situation where you have to buy a gift for someone's birthday but you completely forgot until the very last moment?


What if that someone was somebody who you loved so much, let's say your grandma?

Thats not a good feeling uh?

Don't worry this things happen...

Mmmm... yeah... but what to do?
Maybe you have just some time to quickly go to the mall and get something simple and small...

Unfortunately, you know that It won't work, everyone will notice that you forgot to buy a gift and you just bought the first thing you found on your way to the birthday party.

Well... unless you are a gift wrapping expert ;)...


Yeah... I bet you guys know what this blog post is about.

The "Decorator" design pattern.
Imagine, you want to include some additional functionality to a method but you don't want to have impact in what it is already doing.
What you can do, is create a decorator class, that will wrap the original call to that method, and make all the clients call the decorator instead.



Step 1 - Extract an interface that exposes the function you want to decorate.

 public interface Task {  
  public void doSomething();  
 }  
 public class TaskImpl implements Task {  
  public void doSomething() {  
    System.out.println("doing something!");  
  }  
 }  

Step 2 - Create the decorator

 //Make it implement the interface  
 public class Decorator implements Task {  
   //Use composition to make sure you are decorating the right thing  
   private Task taskToDecorate;  
   public Decorator(Task task) {  
      this.taskToDecorate = task;  
   }  
   //implement the interface, but don't forget the original call  
   public void doSomething() {  
     taskToDecorate.doSomething();  
     System.out.println("www.javing.blogspot.com");  
   }  
 }  

Step 3 - Make the client use the decorator



 public class Client {  
   public static void main(String [] args) {  
           Task taskToDecorate = new TaskImpl();  
           Decorator decorator = new Decorator(taskToDecorate);  
           decorator.doSomething();  
   }  
 }  


I want to mention that on the internet I see that the decorator is almost in every post implemented using inheritance(e.g http://java.dzone.com/articles/design-patterns-decorator).
It also looks interesting and I will not critic it but I will just paste here a link to an interesting debate on stackoverflow: http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance





No comments:

Post a Comment

Share with your friends