Builder Mode)
GOOD: This is applicable when the algorithms used to create complex objects are independent of the components of the objects and their assembly methods.
Example 1:
# Include <string>
# Include <iostream>
# Include <vector>
Using namespace std;
// Final product category
Class Product
{
Private:
Vector <string> m_product;
Public:
Void Add (string strtemp)
{
M_product.push_back (strtemp );
}
Void Show ()
{
Vector <string >:: iterator p = m_product.begin ();
While (p! = M_product.end ())
{
Cout <* p <endl;
P ++;
}
}
};
// Builder base class
Class Builder
{
Public:
Virtual void BuilderA () = 0;
Virtual void BuilderB () = 0;
Virtual Product * GetResult () = 0;
};
// Method 1
Class ConcreteBuilder1: public Builder
{
Private:
Product * m_product;
Public:
ConcreteBuilder1 ()
{
M_product = new Product ();
}
Virtual void BuilderA ()
{
M_product-> Add ("one ");
}
Virtual void BuilderB ()
{
M_product-> Add ("two ");
}
Virtual Product * GetResult ()
{
Return m_product;
}
};
// Method 2
Class ConcreteBuilder2: public Builder
{
Private:
Product * m_product;
Public:
ConcreteBuilder2 ()
{
M_product = new Product ();
}
Virtual void BuilderA ()
{
M_product-> Add ("");
}
Virtual void BuilderB ()
{
M_product-> Add ("B ");
}
Virtual Product * GetResult ()
{
Return m_product;
}
};
// Conductor class
Class Direct
{
Public:
Void Construct (Builder * temp)
{
Temp-> BuilderA ();
Temp-> BuilderB ();
}
};
// Client
Int main ()
{
Direct * p = new Direct ();
Builder * b1 = new ConcreteBuilder1 ();
Builder * b2 = new ConcreteBuilder2 ();
P-> Construct (b1); // call the first method
Product * pb1 = b1-> GetResult ();
Pb1-> Show ();
P-> Construct (b2); // call the second method
Product * PBS = b2-> GetResult ();
PBS-> Show ();
Return 0;
}
Example 2:
# Include <string>
# Include <iostream>
# Include <vector>
Using namespace std;
Class Person
{
Public:
Virtual void CreateHead () = 0;
Virtual void CreateHand () = 0;
Virtual void CreateBody () = 0;
Virtual void CreateFoot () = 0;
};
Class ThinPerson: public Person
{
Public:
Virtual void CreateHead ()
{
Cout <"thin head" <endl;
}
Virtual void CreateHand ()
{
Cout <"thin hand" <endl;
}
Virtual void CreateBody ()
{
Cout <"thin body" <endl;
}
Virtual void CreateFoot ()
{
Cout <"thin foot" <endl;
}
};
Class ThickPerson: public Person
{
Public:
Virtual void CreateHead ()
{
Cout <"ThickPerson head" <endl;
}
Virtual void CreateHand ()
{
Cout <"ThickPerson hand" <endl;
}
Virtual void CreateBody ()
{
Cout <"ThickPerson body" <endl;
}
Virtual void CreateFoot ()
{
Cout <"ThickPerson foot" <endl;
}
};
// Conductor class
Class Direct
{
Private:
Person * p;
Public:
Direct (Person * temp) {p = temp ;}
Void Create ()
{
P-> CreateHead ();
P-> CreateBody ();
P-> CreateHand ();
P-> CreateFoot ();
}
};
// Client code:
Int main ()
{
Person * p = new ThickPerson ();
Direct * d = new Direct (p );
D-> Create ();
Delete d;
Delete p;
Return 0;
}