Builder mode for Java design mode

Source: Internet
Author: User

Let's take an example from the previous section: Producing cars. In the previous section we control the movement of the car through the template method mode, then the demand is endless, now if the boss added additional demand: Car start, stop, whistle engine sound is controlled by the customer, what order he wants in what order, then how to do?

1. Endless renovation of automobiles

If we are to produce two kinds of cars, Mercedes-Benz and BMW, the two cars have similarities, we need to focus on the operation of a single car, this is the boss's concern. We first think, in response to this demand, we have to find a point of entry, that is the product class, each car is a product, then in the product class we can control the order of the car, so that each car can have their own desired order. Based on this, we design the following class diagram:

We see that there is a setsequence method in Carmodel, by passing in a ArrayList to control the order of operation, the Run method is executed according to the order saved in this ArrayList, and then the Mercedes Benz and BMW cars inherit this carmodel respectively. This seems to be a good implementation, it is similar to the previous section of the template method pattern, just a few more ways to set the run order. Let's take a look at the implementation of Carmodel specific code:

public Abstract class Carmodel {private arraylist<string> sequence = new arraylist<string> (); Maintain a ArrayList save Execute command keyword protected abstract void start ();p rotected abstract void Stop ();p rotected abstract void alarm (); protected abstract void Engineboom (); final public void run () {for (int i = 0; i < this.sequence.size (); i + +) {//according to ARRA The corresponding action is executed in the order saved in ylist string actionname = This.sequence.get (i), if (Actionname.equalsignorecase ("start")) {This.start (); Start the car} else if (Actionname.equalsignorecase ("Stop")) {this.stop ();//Stop car} else if (Actionname.equalsignorecase (" Alarm ")) {this.alarm ();//Car horn} else if (Actionname.equalsignorecase (" engine boom ")) {this.engineboom ();//Car Roar}}} Final public void setsequence (arraylist<string> sequence) {//command to get execution order, i.e. a arraylistthis.sequence = sequence;}} 
The Setsequence method in Carmodel allows the customer to set a sequence in which we look at the implementation of the subclass:

public class Benzmodel extends Carmodel {@Overrideprotected void start () {System.out.println ("Mercedes-Benz-Boot ..."); @Overrideprotected void Stop () {System.out.println ("Mercedes stop ..."); @Overrideprotected void Alarm () {System.out.println ("Mercedes Horn ..."); @Overrideprotected void Engineboom () {System.out.println ("Mercedes-Benz Roar");}} BMW is a little bit ... The same
Here we add a test class to implement this requirement:

public class Client {public static void main (string[] args) {Benzmodel Benz = new Benzmodel ();//store Run order arraylist<string > sequence = new arraylist<string> (); Sequence.add ("engine boom"); The boss said: "Before running to roar more handsome!" Sequence.add ("Start"); Sequence.add ("Stop");//We give this order to Mercedes Benz.setsequence (sequence); Benz.run ();}}
This seems to have finished the task successfully, but do not forget that we just meet a demand, if the next demand is the BMW car only roar, and then the next demand is the Mercedes-Benz car only run nonstop ... Wait a minute...... Wouldn't that be to write a test class to implement? Obviously that's not what we want.

We can do this: define a builder for each product model, what order you want to tell the builders directly, build by the builders, and we redesign the class diagram:


We have added a Carbuilder class, it is to assemble the car model, what kind of order is the relevant subclass to complete, we look at the code of Carbuilder:

Public abstract class Carbuilder {//Build a model, you have to give me a sequence requiring public abstract void setsequence (arraylist<string> sequence ),///After setting the order, you can get the vehicle model directly, public abstract Carmodel Getcarmodel ();}
Very simply, each vehicle model has to have a definite order of operation before it can return a vehicle model, the code of the Mercedes Benz and the BMW car assembler is as follows:

public class Benzbuilder extends Carbuilder {private Benzmodel Benz = new Benzmodel ();//Mercedes Benz Model @overridepublic void setsequ ence (arraylist<string> sequence) {this.benz.setSequence (sequence);//Set the running order of the Mercedes Benz model} @Overridepublic Carmodel Getcarmodel () {return This.benz;//return this model to}}//BMW like, do not write ...
Now that the two-car assemblers have been written, let's write a test class to test:

public class Client {public static void main (string[] args) {//store run order arraylist<string> sequence = new arraylist< String> (), Sequence.add ("engine boom"), Sequence.add ("start"); Sequence.add ("Stop"    ); In this order to build a Mercedes Benz Benzbuilder Benzbuilder = new Benzbuilder ();//order to the Mercedes-Benz Assembler Benzbuilder.setsequence (sequence);// Once the Mercedes-Benz Assembler gets the order, it will produce one for you benzmodel Benz = (Benzmodel) Benzbuilder.getcarmodel (); Benz.run ();}}
If I want to produce a BMW, only need to replace the BMW car assembler, so that we do not have direct access to the product class, all access to the Assembly on the line, is not feeling very convenient, I tube you how to produce, I throw you a sequence, you get me a car out, want is this effect!

But the needs of people is a bottomless pit, especially the boss, which day he was unhappy, but also to change the order, this is still very troublesome, four processes (start, stop, alarm, engine boom) according to the arrangement of the combination also has a lot of cases, we can not guarantee the boss want what order, how the whole? Helpless, we can only exert the last killer, find a designer to command the order of each time, and then for each order to specify a code, you say a kind we will give you production immediately! Let's change the class diagram ...

The class diagram looks a little complicated, not really, but on the original basis added a Director class as the role of the designer, responsible for the production of models in accordance with the specified order, such as we want a sequence of Mercedes-Benz, B-Order Mercedes-Benz, a sequence of BMW, b order BMW car ... Wait, let's look at the code for the Director class:

public class Director {private arraylist<string> sequence = new arraylist<string> ();p rivate Benzbuilder Benzbuilder = new Benzbuilder ();p rivate bwmbuilder bwmbuilder = new Bwmbuilder ();//a order Mercedes-Benz public Benzmodel Getabenzmodel () {this.sequence.clear (); This.sequence.add ("Start"); This.sequence.add ("Stop");// Returns a sequence of Mercedes Benz This.benzBuilder.setSequence (sequence); return (Benzmodel) This.benzBuilder.getCarModel ();} B-Order Mercedes Benz Public Benzmodel Getbbenzmodel () {this.sequence.clear (); This.sequence.add ("engine boom"); This.sequence.add ("Start"); This.sequence.add ("Stop");//Mercedes Benz This.benzBuilder.setSequence (sequence) returning B order, return ( Benzmodel) This.benzBuilder.getCarModel ();} C-order BMW public Benzmodel Getcbwmmodel () {this.sequence.clear () This.sequence.add ("Start"); This.sequence.add (" Alarm "); This.sequence.add (" Stop ");//return C-order BMW this.bwmBuilder.setSequence (sequence); return (Benzmodel) This.bwmBuilder.getCarModel ();} D-order BMW public Benzmodel Getdbwmmodel () {this.sequence.clear (); This.sequence.add ("Engine Boom "); This.sequence.add (" Start ");//return D-order BMW this.bwmBuilder.setSequence (sequence); return (Benzmodel) This.bwmBuilder.getCarModel ();} There are a lot of other needs, designers, think of what needs to get you what needs}
With such a designer, our test class is easier to deal with, such as now the boss wants 10,000 class A Mercedes Benz, 100,000 Class B Mercedes Benz, 20000C type BMW, type D do not:

public class Client {public static void main (string[] args) {Director Director = new Director (), for (int i = 0; i < 1000 0; i + +) {Director.getabenzmodel ();} for (int i = 0; i < 100000; i + +) {Director.getbbenzmodel ();} for (int i = 0; i < 20000; i + +) {Director.getcbwmmodel ();}}}
is not very clear and simple, we refactor the final part of the code is simple and clear. This is the builder pattern.

2. Definition of builder Model

Let's take a look at the general definition of builder mode: Separate the construction of a complex object from it representation so, the same construction proces s can create different representations. That is, to separate the construction of a complex object from its representation, so that the same build process can create different representations. For example above, we can construct different cars in the same order. The general class diagram for the builder pattern is as follows:

Product is the final class of products, builder is a builder, and director is the conductor. The Director is responsible for arranging the order of the existing modules and then telling builder to start building.

3. Advantages of the builder model

1) Encapsulation: Use builder mode can be the client does not have to know the details of the internal composition of the product.

2) builders are independent and easy to expand: Benzbuilder and Bmwbuilder are independent of each other and are very advantageous for system expansion.

3) Easy to control the risk of detail: As the concrete builder is independent, it is possible to refine the builder process and not have any impact on the other modules.

4. Usage Scenarios for builder mode

1) The same method, different execution order, produces different event results when the builder mode can be used.

2) Multiple parts or parts can be assembled into an object, but the resulting results do not want to be at the same time, you can use the builder mode.

3) The product class is very complex, or the sequence of calls in the product class produces different performance, when the builder mode can be used.

4) During object creation, some other objects of the system are used, which are not readily available during the creation of the Product object, or can be encapsulated in the builder pattern to encapsulate the object's creation process. This scenario can only be a compensation method, because an object is not easy to obtain, and in the design phase is not found, and to design this pattern to soften the creation process, the design itself has been a problem.

Here, we will find that the builder pattern and the factory method pattern are a bit like. But there's a difference: the builder model focuses on the part type and the assembly process (order), and the Factory mode is to create an object, which is the most different place.

The creator mode introduces so much, if there is a mistake, welcome to the message ~

___________________________________________________________________________________________________________ __________________________________________

-----willing to share and progress together!

-----More articles please see: http://blog.csdn.net/eson_15

Builder mode for Java design mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.