search
HomeBackend DevelopmentPHP Tutorialphp design pattern - builder pattern, php design pattern_PHP tutorial

php design pattern - builder pattern, php design pattern

Requirements analysis:

We received an order from BMW and Mercedes-Benz. They are responsible for defining the parts and models of the products, and we are responsible for production. The simple description of the requirements is like this. We need to design a design pattern for this requirement to better adapt to their needs.

First we need a car model class to define all the required parts. This is called an abstract class. The reason for this is because we may receive orders from more companies, such as Rolls-Royce and Bentley. .

Then each car inherits this abstract class and implements the methods inside.

Next, you need a builder abstract class to define the methods needed to build your own car

Then each car builder inherits this abstract class.

We will think of a construction mode, yes, it is the builder mode. It's perfect to use. Take a look at the builder’s use case diagram

Please note: The method part of the example in this picture does not match my example.

Directly upload the code:

<span>  1</span> <?<span>php
</span><span>  2</span> 
<span>  3</span> <span>abstract</span> <span>class</span><span> carModel{
</span><span>  4</span> 
<span>  5</span>     <span>//</span><span>这里存储所有组装车需要的零件</span>
<span>  6</span>     <span>public</span> <span>$spareParts</span> = <span>array</span><span>();
</span><span>  7</span> 
<span>  8</span>     <span>//</span><span>车的名字</span>
<span>  9</span>     <span>public</span> <span>$carName</span> = ""<span>;
</span><span> 10</span> 
<span> 11</span>     <span>//</span><span>增加轮子部件</span>
<span> 12</span>     <span>public</span> <span>abstract</span> <span>function</span> addLunzi(<span>$xinghao</span><span>);
</span><span> 13</span> 
<span> 14</span>     <span>//</span><span>增加外壳部件</span>
<span> 15</span>     <span>public</span> <span>abstract</span> <span>function</span> addWaike(<span>$xinghao</span><span>);
</span><span> 16</span> 
<span> 17</span>     <span>//</span><span>增加发动机部件</span>
<span> 18</span>     <span>public</span> <span>abstract</span> <span>function</span> addFadongji(<span>$xinghao</span><span>);
</span><span> 19</span> 
<span> 20</span>     <span>//</span><span>获取车,并给车取名字</span>
<span> 21</span>     <span>final</span> <span>public</span> <span>function</span> getCar(<span>$carName</span><span>){
</span><span> 22</span>         <span>if</span>(<span>$this</span>-><span>spareParts){
</span><span> 23</span>             <span>$this</span>->carName = <span>$carName</span><span>;
</span><span> 24</span>             <span>//</span><span>$k 代表部件名字
</span><span> 25</span> <span>            //$v 代表型号</span>
<span> 26</span>             <span>foreach</span>(<span>$this</span>->spareParts <span>as</span> <span>$k</span>=><span>$v</span><span>){
</span><span> 27</span>                 <span>$actionName</span> = "add" . <span>$k</span><span>;
</span><span> 28</span>                 <span>$this</span>-><span>$actionName</span>(<span>$v</span><span>); 
</span><span> 29</span> <span>            }
</span><span> 30</span>         }<span>else</span><span>{
</span><span> 31</span>             <span>throw</span> <span>new</span> <span>Exception</span>("没有汽车部件"<span>);
</span><span> 32</span>             
<span> 33</span> <span>        }
</span><span> 34</span> <span>    }
</span><span> 35</span> <span>}
</span><span> 36</span> 
<span> 37</span> 
<span> 38</span> <span>//</span><span>定义具体的产品</span>
<span> 39</span> <span>class</span> bmwCarModel <span>extends</span><span> carModel{
</span><span> 40</span> 
<span> 41</span>     <span>public</span> <span>$spareParts</span> = <span>array</span><span>();
</span><span> 42</span>     <span>public</span> <span>$carName</span> = ""<span>;
</span><span> 43</span> 
<span> 44</span>     <span>public</span> <span>function</span> addLunzi(<span>$xinghao</span><span>){
</span><span> 45</span>         <span>echo</span> "宝马".<span>$this</span>->carName."的轮子,型号是" . <span>$xinghao</span> . "\n"<span>;
</span><span> 46</span> <span>    }
</span><span> 47</span> 
<span> 48</span>     <span>public</span> <span>function</span> addWaike(<span>$xinghao</span><span>){
</span><span> 49</span>         <span>echo</span> "宝马".<span>$this</span>->carName."的外壳,型号是" . <span>$xinghao</span> . "\n"<span>;
</span><span> 50</span> <span>    }
</span><span> 51</span> 
<span> 52</span>     <span>public</span> <span>function</span> addFadongji(<span>$xinghao</span><span>){
</span><span> 53</span>         <span>echo</span> "宝马".<span>$this</span>->carName."的发动机,型号是 " . <span>$xinghao</span> . "\n"<span>;
</span><span> 54</span> <span>    }
</span><span> 55</span> <span>}
</span><span> 56</span> 
<span> 57</span> 
<span> 58</span> <span>//</span><span>定义具体的产品</span>
<span> 59</span> <span>class</span> benziCarModel <span>extends</span><span> carModel{
</span><span> 60</span> 
<span> 61</span>     <span>public</span> <span>$spareParts</span> = <span>array</span><span>();
</span><span> 62</span>     <span>public</span> <span>$carName</span> = ""<span>;
</span><span> 63</span> 
<span> 64</span>     <span>public</span> <span>function</span> addLunzi(<span>$xinghao</span><span>){
</span><span> 65</span>         <span>echo</span> "奔驰".<span>$this</span>->carName."的轮子,型号是" . <span>$xinghao</span> . "\n"<span>;
</span><span> 66</span> <span>    }
</span><span> 67</span> 
<span> 68</span>     <span>public</span> <span>function</span> addWaike(<span>$xinghao</span><span>){
</span><span> 69</span>         <span>echo</span> "奔驰".<span>$this</span>->carName."的外壳,型号是" . <span>$xinghao</span> . "\n"<span>;
</span><span> 70</span> <span>    }
</span><span> 71</span> 
<span> 72</span>     <span>public</span> <span>function</span> addFadongji(<span>$xinghao</span><span>){
</span><span> 73</span>         <span>echo</span> "奔驰".<span>$this</span>->carName."的发动机,型号是 " . <span>$xinghao</span> . "\n"<span>;
</span><span> 74</span> <span>    }
</span><span> 75</span> <span>}
</span><span> 76</span> 
<span> 77</span> 
<span> 78</span> 
<span> 79</span> <span>//</span><span>定义建造者</span>
<span> 80</span> <span>abstract</span> <span>class</span><span> carBuilder{
</span><span> 81</span>     <span>public</span> <span>abstract</span> <span>function</span> setSpareParts(<span>$partsName</span> , <span>$xinghao</span><span>);
</span><span> 82</span> 
<span> 83</span>     <span>public</span> <span>abstract</span> <span>function</span> getCarModel(<span>$name</span><span>);
</span><span> 84</span> <span>}
</span><span> 85</span> 
<span> 86</span> 
<span> 87</span> <span>class</span> bmwBuilder <span>extends</span><span> carBuilder{
</span><span> 88</span>     <span>private</span> <span>$bmwModel</span><span>;
</span><span> 89</span> 
<span> 90</span>     <span>public</span> <span>function</span><span> __construct(){
</span><span> 91</span>         <span>$this</span>->bmwModel = <span>new</span><span> bmwCarModel();
</span><span> 92</span> <span>    }
</span><span> 93</span> 
<span> 94</span>     <span>public</span> <span>function</span> setSpareParts(<span>$partsName</span> , <span>$xinghao</span><span>){
</span><span> 95</span>         <span>$this</span>->bmwModel->spareParts[<span>$partsName</span>] = <span>$xinghao</span><span>;
</span><span> 96</span> <span>    }
</span><span> 97</span> 
<span> 98</span>     <span>public</span> <span>function</span> getCarModel(<span>$name</span><span>){
</span><span> 99</span>         <span>$this</span>->bmwModel->getCar(<span>$name</span><span>);
</span><span>100</span> <span>    }
</span><span>101</span> <span>}
</span><span>102</span> 
<span>103</span> 
<span>104</span> <span>class</span> benziBuilder <span>extends</span><span> carBuilder{
</span><span>105</span>     <span>private</span> <span>$benziModel</span><span>;
</span><span>106</span> 
<span>107</span>     <span>public</span> <span>function</span><span> __construct(){
</span><span>108</span>         <span>$this</span>->benziModel = <span>new</span><span> benziCarModel();
</span><span>109</span> <span>    }
</span><span>110</span> 
<span>111</span>     <span>public</span> <span>function</span> setSpareParts(<span>$partsName</span> , <span>$xinghao</span><span>){
</span><span>112</span>         <span>$this</span>->bmwModel->spareParts[<span>$partsName</span>] = <span>$xinghao</span><span>;
</span><span>113</span> <span>    }
</span><span>114</span> 
<span>115</span>     <span>public</span> <span>function</span> getCarModel(<span>$name</span><span>){
</span><span>116</span>         <span>$this</span>->bmwModel->getCar(<span>$name</span><span>);
</span><span>117</span> <span>    }
</span><span>118</span> <span>}
</span><span>119</span> 
<span>120</span> 
<span>121</span> 
<span>122</span> <span>//</span><span>模拟客户端调用
</span><span>123</span> 
<span>124</span> <span>//创建一辆宝马车,取名字为宝马x1</span>
<span>125</span> 
<span>126</span> <span>$bmwBuilder</span> = <span>new</span><span> bmwBuilder();
</span><span>127</span> <span>$bmwBuilder</span>->setSpareParts('Lunzi' , '牛逼轮子1号'<span>);
</span><span>128</span> <span>$bmwBuilder</span>->setSpareParts('Waike' , '牛逼外壳1号'<span>);
</span><span>129</span> <span>$bmwBuilder</span>->setSpareParts('Fadongji' , '牛逼发动机1号'<span>);
</span><span>130</span> <span>$bmwBuilder</span>->getCarModel("宝马x1"<span>); 
</span><span>131</span> <span>$bmwBuilder</span>->getCarModel("宝马x1");  <span>//</span><span>连续创建两个宝马x1
</span><span>132</span> 
<span>133</span> <span>//再创建一个宝马 没有外壳 取名为 宝马s5</span>
<span>134</span> <span>$bmwBuilder</span> = <span>new</span><span> bmwBuilder();
</span><span>135</span> <span>$bmwBuilder</span>->setSpareParts('Lunzi' , '牛逼轮子2号'<span>);
</span><span>136</span> <span>$bmwBuilder</span>->setSpareParts('Fadongji' , '牛逼发动机2号'<span>);
</span><span>137</span> <span>$bmwBuilder</span>->getCarModel("宝马s5"<span>); 
</span><span>138</span> <span>$bmwBuilder</span>->getCarModel("宝马s5");  <span>//</span><span>连续创建两个宝马x1</span>

The code can be run directly, and you can try to produce an awesome Mercedes-Benz car.

Definition of Builder Pattern

Builder Pattern is also called Generator Pattern, which is defined as follows:

 Separate the construction of a complex object from its representation so that the same construction process can create different representations. Separate the construction of a complex object from its representation so that the same construction process can create different representations. representation.

The general class diagram of the builder pattern is shown in the figure.

php design pattern - builder pattern, php design pattern_PHP tutorial

In builder mode, there are four characters as follows:

  • Product product category

Usually the template method pattern is implemented, that is, there are template methods and basic methods. Please refer to the template method pattern in the previous chapter. In the example, BenzModel and BMWModel belong to the product category.

  • Builder abstract builder

The construction of standardized products is generally implemented by subclasses. In the example, CarBuilder is an abstract builder.

  • ConcreteBuilder concrete builder

Implement all methods defined by the abstract class and return a component object. In the example, BenzBuilder and BMWBuilder are concrete builders.

  • Director Director

Responsible for arranging the order of existing modules, and then telling the Builder to start building. In the above example, it is our boss. Niucha Company found the boss and said I want this, this, and that type of vehicle model, and then the boss will The order was passed to me, and my team and I started working hard to build, and a project was completed.

Introduction to PHP design patterns

You don’t have to specifically look for ‘php design pattern’, you can look for ‘design pattern’ or ‘java design pattern’ which are easier to find. Because design patterns are not specific to a certain language but an idea, the design ideas you get are the same whether you look at 'php design pattern' or 'java design pattern' or 'design pattern'

What are the benefits of PHP design patterns

If you use UserFactory, you don’t need to know the existence of the User class. The abstract class will help you hide it. If there are more classes in the future, this pattern will be more convenient to maintain. It is recommended that you learn about the abstract factory pattern, factory pattern, and factory. Method patterns, these are all means for reusable programming.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/878815.htmlTechArticlephp design pattern - builder pattern, php design pattern demand analysis: We received an order from BMW and From Mercedes-Benz, they are responsible for defining product parts and models...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)