Let's review the basic concepts of design patterns:
definition
the construction of a complex object is separated from its representation, allowing the same build process to create different representations.
Builders Hide how the product is assembled, so if you need to change the internal representation of a product, you just need to redefine a builder.
Practical Range
1. When creating complex objects, the algorithms should be independent of the components of the object and the way they are assembled.
2. When the construction process must allow the constructed object to have a different representation.
role
in such a design pattern, there are several roles:
1.builder: Specifies an abstract interface for each part that creates a product object.
2.ConcreteBuilder: Implements the builder interface to construct and assemble the parts of the product, define and identify the representations it creates, and provide an interface to retrieve the product.
3.Director: Constructs an object that uses the builder interface.
4.Product: Represents a constructed complex object. ConcreteBuilder creates an internal representation of the product and defines its assembly process, containing the classes that define the components, including the interfaces that assemble the parts into the final product.
Let's take a look at an example:
Requirements:
Draw a villain, have a head, have a body, both hands two feet can.
Initial code:
#-*-encoding: utf-8-*-
#Villain one
puts 'This is the first villain'
puts 'Little Man One: Head'
puts 'Little man one: thin body'
puts 'One villain: both hands'
puts 'Little Man One: Feet'
#Villain two
puts 'This is the second villain'
puts 'Little Man 2: Head'
puts 'Little Man 2: Fat Body'
puts 'Little man two: hands'
puts 'Little man two: feet'
'
Problem: Code duplication, and error prone, lack of arms and legs and so on.
Improved code:
#-*-Encoding:utf-8-*-
#
class Persionbuilder
def head
puts ' end
def body
puts
' End
def arm
puts "end
def leg
puts" end
#Villain one
class Persionthinbuilder < Persionbuilder
def
head puts ' tau '
end
def
body puts ' thin bodies '
def arm
puts ' hands '
end
def leg
puts ' feet ' end
#Villain two
class Persionfatbuilder < Persionbuilder
def
head puts ' heads '
end
def
bodies puts ' fat body '
def arm
puts ' hands '
end
def leg
puts ' feet ' end
#Conductor class class Persiondirect
def initialize (persion)
@persion = persion
end
def create_persion
@ Persion.head
@persion. Body
@persion, arm
@persion. Leg
End
puts ' This is the first villain '
P1 = persionthinbuilder.new
pd1 = Persiondirect.new (p1)
pd1.create_persion puts
' This is the second villain '
P2 = Persionthinbuilder.new
pd2 = persiondirect.new (p2)
pd2.create_persion