Archive for the ‘Design Pattern’ Category

Train Wreck Pattern

May 20, 2013

Well, this might not be a good pattern, and will definitely have pitfalls, but the first look was very much interesting for me. 🙂

public class TrainWreckPattern {
  public static void main(String[] args) {
    new Mailer()
    .to("to@example.com")
    .from("from@exmaple.com")
    .subject("Some subject")
    .body("Some content")
    .send();

  }
}

class Mailer{
  public Mailer to(String address){
    System.out.println("To: "+address);
    return this;
  }
  public Mailer from(String address){
    System.out.println("From: "+address);
    return this;
  }
  public Mailer subject(String sub){
    System.out.println("Subject: "+sub);
    return this;
  }
  public Mailer body(String body){
    System.out.println("Body: "+body);
    return this;
  }
  public void send(){
    System.out.println("Sending ...");
  }
}

This code effectively removes the unnecessary setter methods. Though all the methods are set methods, it in turn returns the current object after setting the attribute. A single line, and all setter methods are called. And in fact in the above example the main operation of sending is also done on the same line of code. Interesting, isn’t it. Well I do not know whether this is an officially recognized pattern, but for me, who want to minimize the coding, this pattern seems to be too much interesting.

That’t it guys. Happy Coding… 🙂

Advertisements

%d bloggers like this: