Definition Separates the construction of a complex object from its representation so that different representations can be created during the same construction process. Such a design pattern is called the builder pattern. Applicability 1. When a complex object is created Algorithm It should be independent from the components of the object and their assembly methods. 2. When the constructor must allow different representations of the constructed object. Role In this design mode, there are several roles: 1 builder: specify an abstract interface for each part of a product object. 2 concretebuilder: implements the builder interface to construct and assemble each part of the product, define and define the representation it creates, and provide an interface for retrieving the product. 3 Director: Construct an object using the builder interface. 4. Product: a complex object to be constructed. Concretebuilder creates an internal representation of the product and defines its assembly process, including the class that defines the components, including the interfaces that assemble these components into the final product. C ++ implementation:
# Include <stdio. h> # Include <Stdlib. h> # Include <Iostream> Using Namespace STD; // Abstract Builder Class Builder { Public : Virtual Void Buildhead () = 0 ; Virtual Void Buildbody () = 0 ; Virtual Void Buildfoot () = 0 ;}; // Specific builder class Class Manbuilder: Public Builder { Public : Void Buildhead () {cout < " Build man head " <Endl ;}; Void Buildbody () {cout < " Build man body " < Endl ;}; Void Buildfoot () {cout < " Build man foot " < Endl ;};}; Class Womanbuilder: Public Builder { Public : Void Buildhead () {cout < " Build woman Head " < Endl ;}; Void Buildbody () {cout < " Build Woman Body " < Endl ;}; Void Buildfoot () {cout < " Build woman foot " < Endl ;};}; // Constructor Class Director { Public : Void Create (builder * Pbuilder) {pbuilder -> Buildhead (); pbuilder -> Buildbody (); pbuilder -> Buildfoot ();}};
Client callCode:
# Include " Stdafx. h " # Include " Builder. h " Int _ Tmain ( Int Argc, _ tchar * Argv []) {Builder * Builder1 = New Manbuilder (); Builder * Builder2 = New Womanbuilder (); Director * Director = New Director (); Director -> Create (builder1); Director -> Create (builder2); Delete ctor; Delete builder1, builder2; getchar (); Return 0 ;}
Here, the commander can build different objects.
Reprinted please indicate the source: http://qq78292959.cnblogs.com/