Purpose:A class can have different components to choose from. These components change frequently but are stable.AlgorithmTo combine them.
Implementation points:Focus on the object construction process, that is, the "Algorithm" mentioned above, and generate the complex objects you need step by step.
UML:
Code:
Class Director
{
Public Homebuilder getbuilder ( String Hometype)
{
If (Hometype = " Simple " )
{
Return New Simplebuilder ();
}
Else
{
Return New Advancedbuilder ();
}
}
}
Public Abstract Class Product
{
Public Abstract String Getname ();
}
Class Bed: Product
{
Public Override String Getname ()
{
Return " Bed " ;
}
}
Class Desk: Product
{
Public Override String Getname ()
{
Return " Desk " ;
}
}
// Stable algorithm: the simple house has two beds, the advanced house has three beds and five tables.
Public Abstract Class Homebuilder
{
Protected Product mybed, mydesk;
Public Abstract Arraylist buildahouse ();
}
Class Simplebuilder: homebuilder
{
Public Override Arraylist buildahouse ()
{
Mybed = New Bed ();
String Name1 = Mybed. getname ();
Arraylist Newhouse = New Arraylist ();
Newhouse. Add ( " This is a simplehouse: " );
For ( Int I = 0 ; I < 2 ; I ++ )
{
Newhouse. Add (name1 );
}
Return Newhouse;
}
}
Class Advancedbuilder: homebuilder
{
Public Override Arraylist buildahouse ()
{
Mybed = New Bed ();
String Name1 = Mybed. getname ();
Mydesk = New Desk ();
String Name2 = Mydesk. getname ();
Arraylist Newhouse = New Arraylist ();
Newhouse. Add ( " This is a advancedhouse: " );
For ( Int I = 0 ; I < 3 ; I ++ )
{
Newhouse. Add (name1 );
}
For ( Int I = 0 ; I < 5 ; I ++ )
{
Newhouse. Add (name2 );
}
Return Newhouse;
}
}
// ----------------------- Run ---------------------------
Class Program
{
Static Void Main ( String [] ARGs)
{
Director dire = New Director ();
Homebuilder builder1 = Director. getbuilder ( " Simple " );
Homebuilder builder2 = Director. getbuilder ( " Advanced " );
Arraylist house1 = Builder1.buildahouse ();
Arraylist house2 = Builder2.buildahouse ();
For ( Int I = 0 ; I < House1.count; I ++ )
{
Console. writeline (house1 [I]. tostring ());
}
For ( Int I = 0 ; I < House2.count; I ++ )
{
Console. writeline (house2 [I]. tostring ());
}
Console. Readline ();
}
}
Note: In the above Code, the two builders are simplebuilder and advancedbuilder respectively. Directory is just a simple factory, and he determines which builder to use. The generator mode is similar to the abstract factory mode. Both return products composed of many methods and objects. The main difference between them is that the abstract factory only returns a series of related objects, while the generator creates a complex object (Newhouse in the previous example) Step by step based on the data provided to him ), he pays more attention to the object building process.