Share

Search Java Code Snippets


  Help us in improving the repository. Add new snippets through 'Submit Code Snippet ' link.





Java - Code Samples

 Sample 1. Usage of Builder Class / Builder Pattern

public class BuggyBread {

   private String element1; // Make them private as it supports stronger encapsulation

   private String element2;

   private BuggyBread(String element1, String element2){ // Make it private so that it can only be used by Builder
      this.element1 = element1;
      this.element2 = element2;
   }

   public static class Builder {
      // Create Builder as nested class as its only supposed to Build BuggyBread objects,
      // Make it public so that it can be accessed from outside
      private String element1; // Make them private as it supports stronger encapsulation

      private String element2;

      Builder(){}; // We have to define this constructor if we need overloaded constructor too and need to initialize without arguments too

      Builder(BuggyBread buggybread){ // overloaded constructor to make things easy
         element1 = buggybread.element1;
         element2 = buggybread.element2;
      }

      Builder withElement1(String element1){ // Builder method to either populate elements or override ( if populated through overloaded constructor )
         this.element1 = element1;
         return this;
      }

      Builder withElement2(String element2){
         this.element2 = element2;
         return this;
      }

      BuggyBread build(){ // method to build BuggyBread object using final contents from Builder
         BuggyBread buggybread = new BuggyBread(element1,element2);
         return buggybread;
      }
   }
}

   Like      Feedback     builder pattern  builder class



Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner



comments powered by Disqus