I. The builder's model
The builder model, as the name suggests, is similar to a construction worker who follows an organized construction sequence (. Piling => Pouring Framing => Masonry => Renovation). The same construction process can be reused for a wide variety of buildings. This is because different materials and designs can perform differently.
The builder pattern, used in the same way as the abstract factory pattern to instantiate complex objects, theThe main difference is:
- The Abstract Factory pattern focuses on instantiating multiple families of complex objects.
- The builder pattern focuses on constructing a complex object in an orderly step-by-step fashion.
II. Code examples
Assembles (builds) a complex object in ordered steps.
Entity Role:
- Abstract Builder (
Builder
) - Specific builders (
Concrete Builder
) - Conductor (
Director
) - Products (
Product
)
import abc class Robot: def __init__(self, head=None, body=None, arms=None, legs=None): = head = body = arms = legs def __str__(self): return f"I'm a robot.:{, , , }" # Abstract builder class RobotBuilder(metaclass=): @ def build_head(self): print("Step 2: Installation of the header") pass @ def build_body(self): print("Step 1: Install the body") pass @ def build_arms(self): print("Step 3: Install the arm.") pass @ def build_legs(self): print("Step 4: Install the feet") pass # Specific builder Doraemon class Doraemon(RobotBuilder): def __init__(self): = Robot() def build_head(self): super().build_head() = "Blue civet head." def build_body(self): super().build_body() = "A body with a bag of treasures." def build_arms(self): super().build_arms() = "Round hands." def build_legs(self): super().build_legs() = "Short legs." # Specific builder Gundam class Gundam(RobotBuilder): def __init__(self): = Robot() def build_head(self): super().build_head() = "White mechanical head." def build_body(self): super().build_body() = "A body of steel." def build_arms(self): super().build_arms() = "Robots with giant cannons." def build_legs(self): super().build_legs() = "Mechanical legs with thrusters." # Commander, set the order of construction class BuildDirector: def build(self, builder): builder.build_body() builder.build_head() builder.build_arms() builder.build_legs() return if __name__ == "__main__": director = BuildDirector() doraemon = Doraemon() print((doraemon)) gundam = Gundam() print((gundam))
This article on Python design patterns in the creation of the builder pattern is introduced to this article, more related Python builder pattern content, please search my previous articles or continue to browse the following related articles I hope you will support me in the future more!