Sunday, March 12, 2017

Builder Design Pattern

Builder Design Pattern
Design Patterns
Creational Design Patterns


We want to produce three types of the same product P. These types are P1, P2 and P3.
P is made from four parts (components), C1, C2, C3 and C4.

The Builder Design Pattern can be employed in three easy steps:

Step 1: We develop one abstract class as Builder with four abstract methods to produce C1, C2, C3 and C4 and one method to return the product.

abstract class Builder {

   abstract ProduceC1( );

   abstract ProduceC2( );
   abstract ProduceC3( );
   abstract ProduceC4( );
   abstract GetProduct( );

}

Step 2: We develop three concrete classes inherited from the class Builder to produce P1, P2 and P3.

class BuilderForP1 : Builder {
   ...
}

class BuilderForP2 : Builder {
   ...
}

class BuilderForP3 : Builder {
   ...
}

Step 3: Then we develop a class as Director with one method to call the methods to make the components in a right order.

class Director {

   void MakeProduct(Builder builder) {

      builder.ProduceC1( );
      builder.ProduceC2( );
      builder.ProduceC3( );
      builder.ProduceC4( );  
   }

}

After the above three steps, we need to use what we developed based on the Builder Design Pattern in order to produce P1, P2 and P3. We develop a Producer class as in the following:

class Producer{
   Director director = new Director( );

   Builder builder1 = BuilderForP1( );

   director.MakeProduct(builder1)
   P1 = builder1.GetProduct( );


   Builder builder2 = BuilderForP2( );

   director.MakeProduct(builder2)
   P2 = builder2.GetProduct( );

   Builder builder3 = BuilderForP3( );

   director.MakeProduct(builder3)
   P2 = builder3.GetProduct( );

}



Copyright ©2017, Software Developer, All rights reserved.
See Contents

No comments:

Post a Comment