Builder Pattern

Builder Patterns: constructor có quá nhiều parameters, dùng builder để group lại cho dễ sử dụng.

public class Hero {
   private final String name;
   private final String weapon;
   private final String armor;
   // get, set  
   public Hero(Builder builder) { =;
      this.weapon = builder.weapon;
      this.armor = builder.armor;

   public static class Builder {
      private final String name;
      private String weapon;
      private String armor;

      public Builder(String name) {
         if (name == null) {
            throw new IllegalArgumentException("name can not be null");
         } = name;

      public Builder withWeapon(String weapon) {
         this.weapon = weapon;
         return this;
      public Builder withArmor(String armor) {
         this.armor = armor;
         return this;

      public Hero build() {
         return new Hero(this);

   } // end Builder
}  //end Hero

Sau đây là cách gọi để khởi tạo

public class App {
   public static void main(String[] args) {
       Hero hero = new Hero.Builder("Xavior").withWeapon("gun").withArmor("leather").build();


One thought on “Builder Pattern

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s