Builder mode of Design Pattern

Source: Internet
Author: User

Builder mode of Design Pattern

Use the factory mode to obtain simple objects.

It is better to use the builder mode when complex objects are obtained and some attributes of objects need to be configured in a complicated way.

 

Here we take building a car as an example. The components of the car can be freely matched.

 

package builder;public class Car {private String engine;private String tire;private String door;private String seat;public void setEngine(String engine) {this.engine = engine;}public void setTire(String tire) {this.tire = tire;}public void setDoor(String door) {this.door = door;}public void setSeat(String seat) {this.seat = seat;}@Overridepublic String toString() {return Car [engine= + engine + , tire= + tire + , door= + door + , seat= + seat + ];}public void show() {System.out.println(toString());}}


 

 

Package builder; public class CarBuilder {private Car car = new Car (); public CarBuilder addEngine (String engine) {car. setEngine (engine); return this;} public CarBuilder addTire (String tire) {car. setTire (tire); return this;} public CarBuilder addDoor (String door) {car. setDoor (door); return this;} public CarBuilder addSeat (String seat) {car. setSeat (seat); return this;}/*** first set the core component of the Car and then call this method */public car build () {return Car ;}}

Package builder; import org. junit. test; public class CarTest {@ Testpublic void test () {Car car = new CarBuilder ()//. addDoor (gorgeous door )//. addEngine (Gold engine )//. addSeat (comfortable seat )//. addTire (dazzling tires )//. build (); car. show ();}}


 

Similar builder uses a lot in android. In some framework configuration objects, you can also see the shadows of the builder 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.