官术网_书友最值得收藏!

Chapter 2. The Builder Pattern

Imagine that we want to create an object that is composed of multiple parts and the composition needs to be done step by step. The object is not complete unless all its parts are fully created. That's where the Builder design pattern can help us. The Builder pattern separates the construction of a complex object from its representation. By keeping the construction separate from the representation, the same construction can be used to create several different representations [GOF95, page 110], [j.mp/builderpat].

A practical example can help us understand what the purpose of the Builder pattern is. Suppose that we want to create an HTML page generator, the basic structure (construction part) of an HTML page is always the same: it begins with <html> and finishes with </html>; inside the HTML section are the <head> and </head> elements, inside the head section are the <title> and </title> elements, and so forth. But the representation of the page can differ. Each page has its own title, its own headings, and different <body> contents. Moreover, the page is usually built in steps: one function adds the title, another adds the main heading, another the footer, and so on. Only after the whole structure of a page is complete can it be shown to the client using a final render function. We can take it even further and extend the HTML generator so that it can generate totally different HTML pages. One page might contain tables, another page might contain image galleries, yet another page contains the contact form, and so on.

The HTML page generation problem can be solved using the Builder pattern. In this pattern, there are two main participants: the builder and the director. The builder is responsible for creating the various parts of the complex object. In the HTML example, these parts are the title, heading, body, and the footer of the page. The director controls the building process using a builder instance. The HTML example means for calling the builder's functions for setting the title, the heading, and so on. Using a different builder instance allows us to create a different HTML page without touching any code of the director.

主站蜘蛛池模板: 仙桃市| 高阳县| 永新县| 绩溪县| 资中县| 海门市| 隆子县| 广平县| 河西区| 台南县| 沧源| 逊克县| 贵港市| 昭通市| 无为县| 长乐市| 云龙县| 什邡市| 鹤峰县| 阿拉尔市| 紫云| 珲春市| 丹阳市| 阳东县| 卫辉市| 秦安县| 章丘市| 澳门| 增城市| 日喀则市| 长宁区| 淳化县| 兰西县| 陆川县| 和静县| 界首市| 镇平县| 南和县| 广灵县| 平舆县| 佛山市|