Examples of builder patterns implemented by Python

  • 2020-12-07 04:06:10
  • OfStack

This article illustrates the builder pattern for the Python implementation. To share for your reference, the details are as follows:


#!/usr/bin/python
# -*- coding:utf-8 -*-
# Builder base class 
class PersonBuilder():
  def BuildHead(self):
    pass
  def BuildBody(self):
    pass
  def BuildArm(self):
    pass
  def BuildLeg(self):
    pass
# Fat man 
class PersonFatBuilder(PersonBuilder):
  type = u' Fat man '
  def BuildHead(self):
    print u' build %s The head of the ' % self.type
  def BuildBody(self):
    print u' build %s The body of ' % self.type
  def BuildArm(self):
    print u' build %s The hand of the ' % self.type
  def BuildLeg(self):
    print u' build %s In the foot ' % self.type
# The skinny man 
class PersonThinBuilder(PersonBuilder):
  type = u' The skinny man '
  def BuildHead(self):
    print u' build %s The head of the ' % self.type
  def BuildBody(self):
    print u' build %s The body of ' % self.type
  def BuildArm(self):
    print u' build %s The hand of the ' % self.type
  def BuildLeg(self):
    print u' build %s In the foot ' % self.type
# commander 
class PersonDirector():
  pb = None;
  def __init__(self, pb):
    self.pb = pb
  def CreatePereson(self):
    self.pb.BuildHead()
    self.pb.BuildBody()
    self.pb.BuildArm()
    self.pb.BuildLeg()
def clientUI():
  pb = PersonThinBuilder()
  pd = PersonDirector(pb)
  pd.CreatePereson()
  pb = PersonFatBuilder()
  pd = PersonDirector(pb)
  pd.CreatePereson()
  return
if __name__ == '__main__':
  clientUI();

Operation results:

[

Build a lean head
Build a lean body
Build a thin hand
Build lean feet
Construct the fat man's head
Build the fat man's body
Build the fat man's hand
Build the fat man's feet

]

For more information about Python, please refer to Python Data Structure and Algorithm Tutorial, Python Socket Programming Skills Summary, Python Function Usage Skills Summary, Python String Manipulation Skills Summary and Python Introductory and Advanced Classic Tutorial.

I hope this article has been helpful in Python programming.


Related articles: