Analysis of the operating principle of the Python builder mode case

The scope of application of the builder mode: you want to create an object composed of multiple parts, and its composition needs to be completed step by step. This object is complete only when all parts are completed. The builder mode represents the separation of the creation and performance of complex objects, so that the same process has different performances.

Assuming we want to create an HTML page generator, we can use the builder mode. In this mode, there are two participants: the builder and the director. The builder is responsible for creating the various components of the object. In the HTML example, these components include: page title, text title, content body, and footer. The leader uses a builder instance to control the construction process. For HTML examples, this refers to calling the builder's function to set the page title, text title, etc. Using different builder instances allows us to create different HTML pages without changing the commander code.

1. Examples in real life

The fast food restaurant uses the builder design pattern. Even if there are multiple hamburgers (classic, cheeseburger, etc.) and different packaging (large, medium, small boxes, etc.), the process of preparing a hamburger and packaging (box or paper bag) is the same. The difference between the two hamburgers lies in performance, not in the process of construction. The commander is the teller, who communicates the instructions on what food to prepare to the staff, the builder.

2. Examples of software

The HTML example mentioned at the beginning of this article has been practically applied in django-widgy. django-widgy is a third-party tree editor extension for Django that can be used as a content management system. It contains a web page builder to create HTML pages with different layouts.

django-query-builder is another Django third-party extension library based on the builder mode, which can be used to dynamically build SQL queries. Using it, we can control all aspects of a query and create different kinds of queries.

3. Application case

If we know that an object must go through multiple steps to create, and require the same construction process can be used to produce different performance, we can use the builder mode. For example, page generators, document converters, user interfaces, etc.

The difference between the factory mode and the builder mode is that the factory mode creates objects in a single step, while the builder mode creates objects in multiple steps, and almost always uses one leader. Some targeted builder pattern implementations do not use commanders, such as Java's StringBuffer.

Another difference is that in the factory mode, a created object is returned immediately; in the builder mode, the client code only explicitly requests the commander to return the final object when needed.

The example of the new computer analogy may help distinguish the builder model from the factory model. Suppose you want to buy a new computer. If you decide to buy a specific pre-configured computer model, for example, the latest Apple 1.4GHz Mac mini, you use the factory model. The specifications of all hardware have been pre-determined by the manufacturer, and the manufacturer knows what to do without consulting you. They usually receive only a single instruction. code show as below



MINI14 = '1.4GHz Mac mini'


class AppleFactory:


class MacMini14:


def __init__(self):


self.memory = 4 # Unit is GB


self.hdd = 500 # Unit is GB


self.gpu = 'Intel HD Graphics 5000'


def __str__(self):


info = ('Model: {}'.format(MINI14),'Memory: {}GB'.format(self.memory),'Hard Disk: {}GB'.format(self.hdd),'Graphics Card: {}'.format(self.gpu))


return '\n'.join(info)


def build_computer(self, model):


if (model == MINI14):


return self.MacMini14()


else:


print("I dont't know how to build {}".format(model))


if __name__ == '__main__':


afac = AppleFactory()


mac_mini = afac.build_computer(MINI14)


print(mac_mini)


Another option is to buy a customized PC. In this case, the builder mode is used. You are the commander, providing instructions to the manufacturer (builder) to explain the ideal computer specifications in your mind.



class Computer:


def __init__(self, serial_number):


self.serial = serial_number


self.memory = None # Unit is GB


self.hdd = None # Unit is GB


self.gpu = None


def __str__(self):


info = ('Memory: {}GB'.format(self.memory),'Hard Disk: {}GB'.format(self.hdd),'Graphics Card: {}'.format(self.gpu))


return '\n'.join(info)


class ComputerBuilder:


def __init__(self):


self.computer = Computer('AG23385193')


def configure_memory(self, amount):


self.computer.memory = amount


def configure_hdd(self, amount):


self.computer.hdd = amount


def configure_gpu(self, gpu_model):


self.computer.gpu = gpu_model


class HardwareEngineer:


def __init__(self):


self.builder = None


def construct_computer(self, memory, hdd, gpu):


self.builder = ComputerBuilder()①


[step for step in (self.builder.configure_memory(memory),self.builder.configure_hdd(hdd),self.builder.configure_gpu(gpu))]


@property


def computer(self):


return self.builder.computer


def main():


engineer = HardwareEngineer()


engineer.construct_computer(hdd=500, memory=8, gpu='GeForce GTX 650 Ti')


computer = engineer.computer


print(computer)


if __name__ == '__main__':


main()


The basic change is the introduction of a builder ComputerBuilder, a commander HardwareEngineer, and the process of assembling a computer step by step, so that different configurations are now supported (note that memory, hdd and gpu are formal parameters and are not preset) .

4. Summary

In this chapter, we learned how to use the builder design pattern. You can use the builder pattern to create objects in some scenarios where the factory pattern (factory method or abstract factory) is not applicable. In the following situations, the builder mode is a better choice than the factory mode.

  • [] Want to create a complex object (the object is composed of multiple parts, and the process of creating the object results in many steps, and perhaps these steps need a specific order).

  • [] Require an object to have many different performances, and hope that the structure and performance of the object have a low degree of coupling

  • [] Want to create objects at different times

We saw how fast food restaurants use the builder mode for food preparation, and how the two third-party Django extension packages (django-widgy and django-query-builder) each use the builder mode to generate HTML pages and dynamic SQL queries. We focused on learning the difference between the builder mode and the factory mode, and clarified the two design modes by comparing the pre-configured (factory) computer and the custom-made (builder) computer to the order.

The above is the whole content of this article, I hope it will be helpful to everyone's study, and I hope you can support it.


Guess you like

Origin blog.51cto.com/14825302/2541101