Sunday, October 24, 2010

Builder

Large value object built in parts, with the help of a director building the object.

A large value object
public class FlightCrew {

 CabinCrew ccrew;
 GroundCrew gcrew;
 PilotCrew pcrew;
 
 public void setCabinCrew(CabinCrew crew){
  ccrew=crew;
 }
 public void setGroundCrew(GroundCrew crew){
  gcrew=crew;
 }
 public void setPilotCrew(PilotCrew crew){
  pcrew=crew;
 }
 public String toString(){
  return ccrew+"\n"+gcrew+" \n"+pcrew;
 }
}
a director to build object part by part
public class FlightDirector {

 public FlightCrew fcrew=new FlightCrew();
 
 private void buildCabinCrew(){
  //read from database available crew
  fcrew.setCabinCrew(new CabinCrew(new String[]{"Tom","Dave"}));
 }
 private  void buildGroundCrew(){
  fcrew.setGroundCrew(new GroundCrew(new String[]{"Charles","John"}));
 }
 private void buildPilotCrew(){
  fcrew.setPilotCrew(new PilotCrew(new String[]{"Austin"}));
 }
 public FlightCrew buildFlightCrew(){
  buildCabinCrew();
  buildGroundCrew();
  buildPilotCrew();
  return fcrew;
 }
} 

the client
public class FlightOperations {

 public static void main(String...strings){
  FlightCrew crew=new FlightDirector().buildFlightCrew();
  System.out.println("The Flight Crew");
  System.out.println(crew);
 }
}
output
The Flight Crew
Cabin Crew:
    Tom,Dave
Ground Crew:
    Charles,John 
Pilot Crew:
    Austin 

Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.

No comments:

Post a Comment