Java Design Patterns Builder Patterns

Introduction

Builder Patterns separate the construction of a complex object from its representation.

Builder Patterns can create immutable objects.

Use case

  • Use builder patterns to create Rectangle

Example


import java.util.LinkedList;

interface Builder {
   void buildStep1();

   void buildStep2();

   void buildStep3();

   StringList GetVehicle();// ww w. jav a  2s  . com

}

class Car implements Builder {
   private StringList product = new StringList();

   @Override
   public void buildStep1() {
      product.Add("Car step1");
   }

   @Override
   public void buildStep2() {
      product.Add("Car step2");
   }

   @Override
   public void buildStep3() {
      product.Add("Car step3");
   }

   @Override
   public StringList GetVehicle() {
      return product;
   }

}

class MotorCycle implements Builder {
   private StringList product = new StringList();

   @Override
   public void buildStep1() {
      product.Add("Motorcycle step1");
   }

   @Override
   public void buildStep2() {
      product.Add("Motorcycle step2");
   }

   @Override
   public void buildStep3() {
      product.Add("Motorcycle step3");
   }

   @Override
   public StringList GetVehicle() {
      return product;
   }
}

class StringList {
   private LinkedList<String>  parts = new LinkedList<String>();

   public StringList() {
     
   }

   public void Add(String part) {
      parts.addLast(part);
   }

   public void Show() {
      for (int i = 0; i < parts.size(); i++) {
         System.out.println(parts.get(i));
      }
   }
}

class Director {
   Builder myBuilder;

   // A series of steps -for the production
   public void build(Builder builder) {
      myBuilder = builder;
      myBuilder.buildStep1();
      myBuilder.buildStep2();
      myBuilder.buildStep3();
   }
}

public class Main {
   public static void main(String[] args) {
      Director director = new Director();

      Builder carBuilder = new Car();
      Builder motorBuilder = new MotorCycle();

      director.build(carBuilder);
      StringList p1 = carBuilder.GetVehicle();
      p1.Show();

      director.build(motorBuilder);
      StringList p2 = motorBuilder.GetVehicle();
      p2.Show();
   }
}



PreviousNext

Related