namespaceRefactoringGuru.DesignPatterns.Builder.Conceptual { // The Builder interface specifies methods for creating the different parts // of the Product objects. publicinterfaceIBuilder { voidBuildPartA(); voidBuildPartB(); voidBuildPartC(); } // The Concrete Builder classes follow the Builder interface and provide // specific implementations of the building steps. Your program may have // several variations of Builders, implemented differently. publicclassConcreteBuilder : IBuilder { private Product _product = new Product(); // A fresh builder instance should contain a blank product object, which // is used in further assembly. publicConcreteBuilder() { this.Reset(); } publicvoidReset() { this._product = new Product(); } // All production steps work with the same product instance. publicvoidBuildPartA() { this._product.Add("PartA1"); } publicvoidBuildPartB() { this._product.Add("PartB1"); } publicvoidBuildPartC() { this._product.Add("PartC1"); } // Concrete Builders are supposed to provide their own methods for // retrieving results. That's because various types of builders may // create entirely different products that don't follow the same // interface. Therefore, such methods cannot be declared in the base // Builder interface (at least in a statically typed programming // language). // // Usually, after returning the end result to the client, a builder // instance is expected to be ready to start producing another product. // That's why it's a usual practice to call the reset method at the end // of the `GetProduct` method body. However, this behavior is not // mandatory, and you can make your builders wait for an explicit reset // call from the client code before disposing of the previous result. public Product GetProduct() { Product result = this._product;
this.Reset();
return result; } } // It makes sense to use the Builder pattern only when your products are // quite complex and require extensive configuration. // // Unlike in other creational patterns, different concrete builders can // produce unrelated products. In other words, results of various builders // may not always follow the same interface. publicclassProduct { private List<object> _parts = new List<object>(); publicvoidAdd(string part) { this._parts.Add(part); } publicstringListParts() { string str = string.Empty;
for (int i = 0; i < this._parts.Count; i++) { str += this._parts[i] + ", "; }
str = str.Remove(str.Length - 2); // removing last ",c"
return"Product parts: " + str + "\n"; } } // The Director is only responsible for executing the building steps in a // particular sequence. It is helpful when producing products according to a // specific order or configuration. Strictly speaking, the Director class is // optional, since the client can control builders directly. publicclassDirector { private IBuilder _builder; public IBuilder Builder { set { _builder = value; } } // The Director can construct several product variations using the same // building steps. publicvoidBuildMinimalViableProduct() { this._builder.BuildPartA(); } publicvoidBuildFullFeaturedProduct() { this._builder.BuildPartA(); this._builder.BuildPartB(); this._builder.BuildPartC(); } }
classProgram { staticvoidMain(string[] args) { // The client code creates a builder object, passes it to the // director and then initiates the construction process. The end // result is retrieved from the builder object. var director = new Director(); var builder = new ConcreteBuilder(); director.Builder = builder; Console.WriteLine("Standard basic product:"); director.BuildMinimalViableProduct(); Console.WriteLine(builder.GetProduct().ListParts());
Console.WriteLine("Standard full featured product:"); director.BuildFullFeaturedProduct(); Console.WriteLine(builder.GetProduct().ListParts());
// Remember, the Builder pattern can be used without a Director // class. Console.WriteLine("Custom product:"); builder.BuildPartA(); builder.BuildPartC(); Console.Write(builder.GetProduct().ListParts()); } } }
Output.txt: 执行结果
1 2 3 4 5 6 7 8
Standard basic product: Product parts: PartA1
Standard full featured product: Product parts: PartA1, PartB1, PartC1
Custom product: Product parts: PartA1, PartC1
在 C++ 中使用模式
复杂度: ★★☆
流行度: ★★★
使用示例: 生成器模式是 C++ 世界中的一个著名模式。 当你需要创建一个可能有许多配置选项的对象时, 该模式会特别有用。
/** * It makes sense to use the Builder pattern only when your products are quite * complex and require extensive configuration. * * Unlike in other creational patterns, different concrete builders can produce * unrelated products. In other words, results of various builders may not * always follow the same interface. */
/** * The Builder interface specifies methods for creating the different parts of * the Product objects. */ classBuilder{ public: virtual ~Builder(){} virtualvoidProducePartA()const=0; virtualvoidProducePartB()const=0; virtualvoidProducePartC()const=0; }; /** * The Concrete Builder classes follow the Builder interface and provide * specific implementations of the building steps. Your program may have several * variations of Builders, implemented differently. */ classConcreteBuilder1 : public Builder{ private:
Product1* product;
/** * A fresh builder instance should contain a blank product object, which is * used in further assembly. */ public:
ConcreteBuilder1(){ this->Reset(); }
~ConcreteBuilder1(){ delete product; }
voidReset(){ this->product= newProduct1(); } /** * All production steps work with the same product instance. */
/** * Concrete Builders are supposed to provide their own methods for * retrieving results. That's because various types of builders may create * entirely different products that don't follow the same interface. * Therefore, such methods cannot be declared in the base Builder interface * (at least in a statically typed programming language). Note that PHP is a * dynamically typed language and this method CAN be in the base interface. * However, we won't declare it there for the sake of clarity. * * Usually, after returning the end result to the client, a builder instance * is expected to be ready to start producing another product. That's why * it's a usual practice to call the reset method at the end of the * `getProduct` method body. However, this behavior is not mandatory, and * you can make your builders wait for an explicit reset call from the * client code before disposing of the previous result. */
/** * Please be careful here with the memory ownership. Once you call * GetProduct the user of this function is responsable to release this * memory. Here could be a better option to use smart pointers to avoid * memory leaks */
/** * The Director is only responsible for executing the building steps in a * particular sequence. It is helpful when producing products according to a * specific order or configuration. Strictly speaking, the Director class is * optional, since the client can control builders directly. */ classDirector{ /** * @var Builder */ private: Builder* builder; /** * The Director works with any builder instance that the client code passes * to it. This way, the client code may alter the final type of the newly * assembled product. */
/** * The Director can construct several product variations using the same * building steps. */
voidBuildMinimalViableProduct(){ this->builder->ProducePartA(); } voidBuildFullFeaturedProduct(){ this->builder->ProducePartA(); this->builder->ProducePartB(); this->builder->ProducePartC(); } }; /** * The client code creates a builder object, passes it to the director and then * initiates the construction process. The end result is retrieved from the * builder object. */ /** * I used raw pointers for simplicity however you may prefer to use smart * pointers here */ voidClientCode(Director& director) { ConcreteBuilder1* builder = newConcreteBuilder1(); director.set_builder(builder); std::cout << "Standard basic product:\n"; director.BuildMinimalViableProduct(); Product1* p= builder->GetProduct(); p->ListParts(); delete p;
std::cout << "Standard full featured product:\n"; director.BuildFullFeaturedProduct();
// Remember, the Builder pattern can be used without a Director class. std::cout << "Custom product:\n"; builder->ProducePartA(); builder->ProducePartC(); p=builder->GetProduct(); p->ListParts(); delete p;
/** * Unlike other creational patterns, Builder can construct unrelated products, * which don't have the common interface. * * In this case we build a user manual for a car, using the same steps as we * built a car. This allows to produce manuals for specific car models, * configured with different features. */ publicclassCarManualBuilderimplementsBuilder{ private CarType type; privateint seats; private Engine engine; private Transmission transmission; private TripComputer tripComputer; private GPSNavigator gpsNavigator;
/** * Car manual is another product. Note that it does not have the same ancestor * as a Car. They are not related. */ publicclassManual { privatefinal CarType carType; privatefinalint seats; privatefinal Engine engine; privatefinal Transmission transmission; privatefinal TripComputer tripComputer; privatefinal GPSNavigator gpsNavigator;
/** * Director defines the order of building steps. It works with a builder object * through common Builder interface. Therefore it may not know what product is * being built. */ publicclassDirector {
// Director gets the concrete builder object from the client // (application code). That's because application knows better which // builder to use to get a specific product. CarBuilderbuilder=newCarBuilder(); director.constructSportsCar(builder);
// The final product is often retrieved from a builder object, since // Director is not aware and not dependent on concrete builders and // products. Carcar= builder.getResult(); System.out.println("Car built:\n" + car.getCarType());
// Director may know several building recipes. director.constructSportsCar(manualBuilder); ManualcarManual= manualBuilder.getResult(); System.out.println("\nCar manual built:\n" + carManual.print()); }
}
OutputDemo.txt: 执行结果
1 2 3 4 5 6 7 8 9 10
Car built: SPORTS_CAR
Car manual built: Type of car: SPORTS_CAR Count of seats: 2 Engine: volume - 3.0; mileage - 0.0 Transmission: SEMI_AUTOMATIC Trip Computer: Functional GPS Navigator: Functional
/** * The Builder interface specifies methods for creating the different parts of * the Product objects. */ interfaceBuilder { publicfunctionproducePartA(): void;
publicfunctionproducePartB(): void;
publicfunctionproducePartC(): void; }
/** * The Concrete Builder classes follow the Builder interface and provide * specific implementations of the building steps. Your program may have several * variations of Builders, implemented differently. */ classConcreteBuilder1implementsBuilder { private$product;
/** * A fresh builder instance should contain a blank product object, which is * used in further assembly. */ publicfunction__construct() { $this->reset(); }
/** * Concrete Builders are supposed to provide their own methods for * retrieving results. That's because various types of builders may create * entirely different products that don't follow the same interface. * Therefore, such methods cannot be declared in the base Builder interface * (at least in a statically typed programming language). Note that PHP is a * dynamically typed language and this method CAN be in the base interface. * However, we won't declare it there for the sake of clarity. * * Usually, after returning the end result to the client, a builder instance * is expected to be ready to start producing another product. That's why * it's a usual practice to call the reset method at the end of the * `getProduct` method body. However, this behavior is not mandatory, and * you can make your builders wait for an explicit reset call from the * client code before disposing of the previous result. */ publicfunctiongetProduct(): Product1 { $result = $this->product; $this->reset();
return$result; } }
/** * It makes sense to use the Builder pattern only when your products are quite * complex and require extensive configuration. * * Unlike in other creational patterns, different concrete builders can produce * unrelated products. In other words, results of various builders may not * always follow the same interface. */ classProduct1 { public$parts = [];
/** * The Director is only responsible for executing the building steps in a * particular sequence. It is helpful when producing products according to a * specific order or configuration. Strictly speaking, the Director class is * optional, since the client can control builders directly. */ classDirector { /** * @var Builder */ private$builder;
/** * The Director works with any builder instance that the client code passes * to it. This way, the client code may alter the final type of the newly * assembled product. */ publicfunctionsetBuilder(Builder $builder): void { $this->builder = $builder; }
/** * The Director can construct several product variations using the same * building steps. */ publicfunctionbuildMinimalViableProduct(): void { $this->builder->producePartA(); }
/** * The client code creates a builder object, passes it to the director and then * initiates the construction process. The end result is retrieved from the * builder object. */ functionclientCode(Director $director) { $builder = newConcreteBuilder1(); $director->setBuilder($builder);
echo"Standard full featured product:\n"; $director->buildFullFeaturedProduct(); $builder->getProduct()->listParts();
// Remember, the Builder pattern can be used without a Director class. echo"Custom product:\n"; $builder->producePartA(); $builder->producePartC(); $builder->getProduct()->listParts(); }
$director = newDirector(); clientCode($director);
Output.txt: 执行结果
1 2 3 4 5 6 7 8
Standard basic product: Product parts: PartA1
Standard full featured product: Product parts: PartA1, PartB1, PartC1
/** * The Builder interface declares a set of methods to assemble an SQL query. * * All of the construction steps are returning the current builder object to * allow chaining: $builder->select(...)->where(...) */ interfaceSQLQueryBuilder { publicfunctionselect(string$table, array$fields): SQLQueryBuilder;
/** * Each Concrete Builder corresponds to a specific SQL dialect and may implement * the builder steps a little bit differently from the others. * * This Concrete Builder can build SQL queries compatible with MySQL. */ classMysqlQueryBuilderimplementsSQLQueryBuilder { protected$query;
protectedfunctionreset(): void { $this->query = new \stdClass(); }
/** * Build a base SELECT query. */ publicfunctionselect(string$table, array$fields): SQLQueryBuilder { $this->reset(); $this->query->base = "SELECT " . implode(", ", $fields) . " FROM " . $table; $this->query->type = 'select';
return$this; }
/** * Add a WHERE condition. */ publicfunctionwhere(string$field, string$value, string$operator = '='): SQLQueryBuilder { if (!in_array($this->query->type, ['select', 'update', 'delete'])) { thrownew\Exception("WHERE can only be added to SELECT, UPDATE OR DELETE"); } $this->query->where[] = "$field$operator '$value'";
return$this; }
/** * Add a LIMIT constraint. */ publicfunctionlimit(int$start, int$offset): SQLQueryBuilder { if (!in_array($this->query->type, ['select'])) { thrownew\Exception("LIMIT can only be added to SELECT"); } $this->query->limit = " LIMIT " . $start . ", " . $offset;
return$this; }
/** * Get the final query string. */ publicfunctiongetSQL(): string { $query = $this->query; $sql = $query->base; if (!empty($query->where)) { $sql .= " WHERE " . implode(' AND ', $query->where); } if (isset($query->limit)) { $sql .= $query->limit; } $sql .= ";"; return$sql; } }
/** * This Concrete Builder is compatible with PostgreSQL. While Postgres is very * similar to Mysql, it still has several differences. To reuse the common code, * we extend it from the MySQL builder, while overriding some of the building * steps. */ classPostgresQueryBuilderextendsMysqlQueryBuilder { /** * Among other things, PostgreSQL has slightly different LIMIT syntax. */ publicfunctionlimit(int$start, int$offset): SQLQueryBuilder { parent::limit($start, $offset);
/** * Note that the client code uses the builder object directly. A designated * Director class is not necessary in this case, because the client code needs * different queries almost every time, so the sequence of the construction * steps cannot be easily reused. * * Since all our query builders create products of the same type (which is a * string), we can interact with all builders using their common interface. * Later, if we implement a new Builder class, we will be able to pass its * instance to the existing client code without breaking it thanks to the * SQLQueryBuilder interface. */ functionclientCode(SQLQueryBuilder $queryBuilder) { // ...
/** * The application selects the proper query builder type depending on a current * configuration or the environment settings. */ // if ($_ENV['database_type'] == 'postgres') { // $builder = new PostgresQueryBuilder(); } else { // $builder = new MysqlQueryBuilder(); } // // clientCode($builder);
echo"Testing MySQL query builder:\n"; clientCode(newMysqlQueryBuilder());
classConcreteBuilder1(Builder): """ The Concrete Builder classes follow the Builder interface and provide specific implementations of the building steps. Your program may have several variations of Builders, implemented differently. """
def__init__(self) -> None: """ A fresh builder instance should contain a blank product object, which is used in further assembly. """ self.reset()
@property defproduct(self) -> Product1: """ Concrete Builders are supposed to provide their own methods for retrieving results. That's because various types of builders may create entirely different products that don't follow the same interface. Therefore, such methods cannot be declared in the base Builder interface (at least in a statically typed programming language). Usually, after returning the end result to the client, a builder instance is expected to be ready to start producing another product. That's why it's a usual practice to call the reset method at the end of the `getProduct` method body. However, this behavior is not mandatory, and you can make your builders wait for an explicit reset call from the client code before disposing of the previous result. """ product = self._product self.reset() return product
classProduct1(): """ It makes sense to use the Builder pattern only when your products are quite complex and require extensive configuration. Unlike in other creational patterns, different concrete builders can produce unrelated products. In other words, results of various builders may not always follow the same interface. """
classDirector: """ The Director is only responsible for executing the building steps in a particular sequence. It is helpful when producing products according to a specific order or configuration. Strictly speaking, the Director class is optional, since the client can control builders directly. """
@builder.setter defbuilder(self, builder: Builder) -> None: """ The Director works with any builder instance that the client code passes to it. This way, the client code may alter the final type of the newly assembled product. """ self._builder = builder
""" The Director can construct several product variations using the same building steps. """
if __name__ == "__main__": """ The client code creates a builder object, passes it to the director and then initiates the construction process. The end result is retrieved from the builder object. """
director = Director() builder = ConcreteBuilder1() director.builder = builder
print("Standard full featured product: ") director.build_full_featured_product() builder.product.list_parts()
print("\n")
# Remember, the Builder pattern can be used without a Director class. print("Custom product: ") builder.produce_part_a() builder.produce_part_b() builder.product.list_parts()
Output.txt: 执行结果
1 2 3 4 5 6 7 8
Standard basic product: Product parts: PartA1
Standard full featured product: Product parts: PartA1, PartB1, PartC1
# The Builder interface specifies methods for creating the different parts of # the Product objects. classBuilder # @abstract defproduce_part_a raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'" end
# @abstract defproduce_part_b raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'" end
# @abstract defproduce_part_c raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'" end end
# The Concrete Builder classes follow the Builder interface and provide specific # implementations of the building steps. Your program may have several # variations of Builders, implemented differently. classConcreteBuilder1 < Builder # A fresh builder instance should contain a blank product object, which is # used in further assembly. definitialize reset end
defreset @product = Product1.new end
# Concrete Builders are supposed to provide their own methods for retrieving # results. That's because various types of builders may create entirely # different products that don't follow the same interface. Therefore, such # methods cannot be declared in the base Builder interface (at least in a # statically typed programming language). # # Usually, after returning the end result to the client, a builder instance is # expected to be ready to start producing another product. That's why it's a # usual practice to call the reset method at the end of the `getProduct` # method body. However, this behavior is not mandatory, and you can make your # builders wait for an explicit reset call from the client code before # disposing of the previous result. defproduct product = @product reset product end
defproduce_part_a @product.add('PartA1') end
defproduce_part_b @product.add('PartB1') end
defproduce_part_c @product.add('PartC1') end end
# It makes sense to use the Builder pattern only when your products are quite # complex and require extensive configuration. # # Unlike in other creational patterns, different concrete builders can produce # unrelated products. In other words, results of various builders may not always # follow the same interface. classProduct1 definitialize @parts = [] end
# @param [String] part defadd(part) @parts << part end
deflist_parts print "Product parts: #{@parts.join(', ')}" end end
# The Director is only responsible for executing the building steps in a # particular sequence. It is helpful when producing products according to a # specific order or configuration. Strictly speaking, the Director class is # optional, since the client can control builders directly. classDirector # @return [Builder] attr_accessor:builder
definitialize @builder = nil end
# The Director works with any builder instance that the client code passes to # it. This way, the client code may alter the final type of the newly # assembled product. defbuilder=(builder) @builder = builder end
# The Director can construct several product variations using the same # building steps.
defbuild_minimal_viable_product @builder.produce_part_a end
defbuild_full_featured_product @builder.produce_part_a @builder.produce_part_b @builder.produce_part_c end end
# The client code creates a builder object, passes it to the director and then # initiates the construction process. The end result is retrieved from the # builder object.
director = Director.new builder = ConcreteBuilder1.new director.builder = builder
puts 'Standard full featured product: ' director.build_full_featured_product builder.product.list_parts
puts "\n\n"
# Remember, the Builder pattern can be used without a Director class. puts 'Custom product: ' builder.produce_part_a builder.produce_part_b builder.product.list_parts
output.txt: 执行结果
1 2 3 4 5 6 7 8
Standard basic product: Product parts: PartA1
Standard full featured product: Product parts: PartA1, PartB1, PartC1
Custom product: Product parts: PartA1, PartB1
在 Swift 中使用模式
复杂度: ★★☆
流行度: ★★★
使用示例: 生成器模式是 Swift 世界中的一个著名模式。 当你需要创建一个可能有许多配置选项的对象时, 该模式会特别有用。
/// The Concrete Builder classes follow the Builder interface and provide /// specific implementations of the building steps. Your program may have /// several variations of Builders, implemented differently. classConcreteBuilder1: Builder {
/// A fresh builder instance should contain a blank product object, which is /// used in further assembly. privatevar product =Product1()
funcreset() { product =Product1() }
/// All production steps work with the same product instance. funcproducePartA() { product.add(part: "PartA1") }
/// Concrete Builders are supposed to provide their own methods for /// retrieving results. That's because various types of builders may create /// entirely different products that don't follow the same interface. /// Therefore, such methods cannot be declared in the base Builder interface /// (at least in a statically typed programming language). /// /// Usually, after returning the end result to the client, a builder /// instance is expected to be ready to start producing another product. /// That's why it's a usual practice to call the reset method at the end of /// the `getProduct` method body. However, this behavior is not mandatory, /// and you can make your builders wait for an explicit reset call from the /// client code before disposing of the previous result. funcretrieveProduct() -> Product1 { let result =self.product reset() return result } }
/// The Director is only responsible for executing the building steps in a /// particular sequence. It is helpful when producing products according to a /// specific order or configuration. Strictly speaking, the Director class is /// optional, since the client can control builders directly. classDirector {
privatevar builder: Builder?
/// The Director works with any builder instance that the client code passes /// to it. This way, the client code may alter the final type of the newly /// assembled product. funcupdate(builder: Builder) { self.builder = builder }
/// The Director can construct several product variations using the same /// building steps. funcbuildMinimalViableProduct() { builder?.producePartA() }
/// It makes sense to use the Builder pattern only when your products are quite /// complex and require extensive configuration. /// /// Unlike in other creational patterns, different concrete builders can produce /// unrelated products. In other words, results of various builders may not /// always follow the same interface. classProduct1 {
/// The client code creates a builder object, passes it to the director and then /// initiates the construction process. The end result is retrieved from the /// builder object. classClient { // ... staticfuncsomeClientCode(director: Director) { let builder =ConcreteBuilder1() director.update(builder: builder) print("Standard basic product:") director.buildMinimalViableProduct() print(builder.retrieveProduct().listParts())
print("Standard full featured product:") director.buildFullFeaturedProduct() print(builder.retrieveProduct().listParts())
// Remember, the Builder pattern can be used without a Director class. print("Custom product:") builder.producePartA() builder.producePartC() print(builder.retrieveProduct().listParts()) } // ... }
/// Let's see how it all comes together. classBuilderConceptual: XCTestCase {
functestBuilderConceptual() { let director =Director() Client.someClientCode(director: director) } }
Output.txt: 执行结果
1 2 3 4 5 6 7 8
Standard basic product: Product parts: PartA1
Standard full featured product: Product parts: PartA1, PartB1, PartC1
print("RealmProvider: Retrieving data from Realm...")
for item in operations { switch item { case .filter(_): print("RealmProvider: executing the 'filter' operation.") /// Use Realm instance to filter results. break case .limit(_): print("RealmProvider: executing the 'limit' operation.") /// Use Realm instance to limit results. break } }
print("CoreDataProvider: Retrieving data from CoreData...")
for item in operations { switch item { case .filter(_): print("CoreDataProvider: executing the 'filter' operation.") /// Set a 'predicate' for a NSFetchRequest. break case .limit(_): print("CoreDataProvider: executing the 'limit' operation.") /// Set a 'fetchLimit' for a NSFetchRequest. break case .includesPropertyValues(_): print("CoreDataProvider: executing the 'includesPropertyValues' operation.") /// Set an 'includesPropertyValues' for a NSFetchRequest. break } }
/// Execute a NSFetchRequest and return results. return [] } }
protocolDomainModel { /// The protocol groups domain models to the common interface }
privatestructUser: DomainModel { let id: Int let age: Int let email: String }
classBuilderRealWorld: XCTestCase {
functestBuilderRealWorld() { print("Client: Start fetching data from Realm") clientCode(builder: RealmQueryBuilder<User>())
print()
print("Client: Start fetching data from CoreData") clientCode(builder: CoreDataQueryBuilder<User>()) }
let results = builder.filter({ $0.age <20 }) .limit(1) .fetch()
print("Client: I have fetched: "+String(results.count) +" records.") } }
Output.txt: 执行结果
1 2 3 4 5 6 7 8 9 10 11 12 13
Client: Start fetching data from Realm RealmQueryBuilder: Initializing CoreDataProvider with 2 operations: RealmProvider: Retrieving data from Realm... RealmProvider: executing the 'filter' operation. RealmProvider: executing the 'limit' operation. Client: I have fetched: 0 records.
Client: Start fetching data from CoreData CoreDataQueryBuilder: Initializing CoreDataProvider with 2 operations. CoreDataProvider: Retrieving data from CoreData... CoreDataProvider: executing the 'filter' operation. CoreDataProvider: executing the 'limit' operation. Client: I have fetched: 0 records.
/** * The Builder interface specifies methods for creating the different parts of * the Product objects. */ interfaceBuilder { producePartA(): void; producePartB(): void; producePartC(): void; }
/** * The Concrete Builder classes follow the Builder interface and provide * specific implementations of the building steps. Your program may have several * variations of Builders, implemented differently. */ classConcreteBuilder1implementsBuilder { privateproduct: Product1;
/** * A fresh builder instance should contain a blank product object, which is * used in further assembly. */ constructor() { this.reset(); }
/** * Concrete Builders are supposed to provide their own methods for * retrieving results. That's because various types of builders may create * entirely different products that don't follow the same interface. * Therefore, such methods cannot be declared in the base Builder interface * (at least in a statically typed programming language). * * Usually, after returning the end result to the client, a builder instance * is expected to be ready to start producing another product. That's why * it's a usual practice to call the reset method at the end of the * `getProduct` method body. However, this behavior is not mandatory, and * you can make your builders wait for an explicit reset call from the * client code before disposing of the previous result. */ publicgetProduct(): Product1 { const result = this.product; this.reset(); return result; } }
/** * It makes sense to use the Builder pattern only when your products are quite * complex and require extensive configuration. * * Unlike in other creational patterns, different concrete builders can produce * unrelated products. In other words, results of various builders may not * always follow the same interface. */ classProduct1 { publicparts: string[] = [];
/** * The Director is only responsible for executing the building steps in a * particular sequence. It is helpful when producing products according to a * specific order or configuration. Strictly speaking, the Director class is * optional, since the client can control builders directly. */ classDirector { privatebuilder: Builder;
/** * The Director works with any builder instance that the client code passes * to it. This way, the client code may alter the final type of the newly * assembled product. */ publicsetBuilder(builder: Builder): void { this.builder = builder; }
/** * The Director can construct several product variations using the same * building steps. */ publicbuildMinimalViableProduct(): void { this.builder.producePartA(); }
/** * The client code creates a builder object, passes it to the director and then * initiates the construction process. The end result is retrieved from the * builder object. */ functionclientCode(director: Director) { const builder = newConcreteBuilder1(); director.setBuilder(builder);
console.log('Standard full featured product:'); director.buildFullFeaturedProduct(); builder.getProduct().listParts();
// Remember, the Builder pattern can be used without a Director class. console.log('Custom product:'); builder.producePartA(); builder.producePartC(); builder.getProduct().listParts(); }
const director = newDirector(); clientCode(director);
Output.txt: 执行结果
1 2 3 4 5 6 7 8
Standard basic product: Product parts: PartA1
Standard full featured product: Product parts: PartA1, PartB1, PartC1
director := newDirector(normalBuilder) normalHouse := director.buildHouse()
fmt.Printf("Normal House Door Type: %s\n", normalHouse.doorType) fmt.Printf("Normal House Window Type: %s\n", normalHouse.windowType) fmt.Printf("Normal House Num Floor: %d\n", normalHouse.floor)
fmt.Printf("\nIgloo House Door Type: %s\n", iglooHouse.doorType) fmt.Printf("Igloo House Window Type: %s\n", iglooHouse.windowType) fmt.Printf("Igloo House Num Floor: %d\n", iglooHouse.floor)
}
output.txt: 执行结果
1 2 3 4 5 6 7
Normal House Door Type: Wooden Door Normal House Window Type: Wooden Window Normal House Num Floor: 2
Igloo House Door Type: Snow Door Igloo House Window Type: Snow Window Igloo House Num Floor: 1