The builder pattern separates the parts themselves from their assembly processes, and focuses on how to create a complex object with multiple components in step-by-step, and the user simply needs to specify the type of the complex object to get the object, without having to know the specifics of the construction itself.
Builder mode: Separates the construction of a complex object from its representation so that the same build process can create different representations.
Definition of builder Mode:
Separating the client from the creation of complex objects with multiple parts, the client does not need to know the internal components and assembly methods of complex objects, only need to know the type of builders required;
Focus on how to create a complex object incrementally, and different builders define different creation processes;
Structure of the builder pattern:
The builder pattern consists of the following 4 roles:
Builder (abstract builder)
ConcreteBuilder (Concrete builder)
Product (Products)
Director (conductor)
Example:
/// <summary>///Abstract Builder/// </summary> Public Abstract classbuilder{ Public Abstract voidBuilderparta (); Public Abstract voidBUILDERPARTB (); Public Abstract voidBUILDERPARTC (); /// <summary> /////Create product Objects/// </summary> protectedProduct Product =NewProduct (); /// <summary> ///Return Product Object/// </summary> /// <returns></returns> PublicProduct GetResult () {returnproduct; }}
/// <summary>///Product Category/// </summary> Public classproduct{//Production of Products Public stringParta {Get;Set; } Public stringPartB {Get;Set; } Public stringPARTC {Get;Set; }}
/// <summary>///Concrete Builders/// </summary> Public classconcretebuilder:builder{/// <summary> ///Product A/// </summary> Public Override voidBuilderparta () {product. Parta="A1"; Console.WriteLine ("production of A1 products"); } /// <summary> ///Product B/// </summary> Public Override voidBUILDERPARTB () {product. PartB="B1"; Console.WriteLine ("production of B1 products"); } /// <summary> ///Product C/// </summary> Public Override voidBUILDERPARTC () {product. PARTC="C1"; Console.WriteLine ("production of C1 products"); }}
/// <summary>///Conductor/// </summary> Public classdirector{PrivateBuilder _builder; PublicDirector (Builder builder) { This. _builder =Builder; } Public voidSetbuilder (Builder builder) { This. _builder =Builder; } /// <summary> ///Product Building and assembly methods/// </summary> /// <returns></returns> PublicProduct Construct () {_builder. Builderparta (); _builder. BUILDERPARTB (); _builder. BUILDERPARTC (); return_builder. GetResult (); }}
// Client Calls New new= director. Construct ();
The builder pattern for C # Design Patterns