Created
February 16, 2014 22:24
-
-
Save DavidTPate/9041496 to your computer and use it in GitHub Desktop.
An example of the Builder Pattern in Java for a simple car class.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class Car { | |
| int year; | |
| String make; | |
| String model; | |
| String carType; | |
| public static class Builder { | |
| int year; | |
| String make; | |
| String model; | |
| String carType; | |
| public Builder year(int year) { | |
| this.year = year; | |
| return this; | |
| } | |
| public Builder make(String make) { | |
| this.make = make; | |
| return this; | |
| } | |
| public Builder model(String model) { | |
| this.model = model; | |
| return this; | |
| } | |
| public Builder carType(String carType) { | |
| this.carType = carType; | |
| return this; | |
| } | |
| public Car build() { | |
| return new Car(this); | |
| } | |
| } | |
| private Car(Builder builder) { | |
| this.year = builder.year; | |
| this.make = builder.make; | |
| this.model = builder.model; | |
| this.carType = builder.carType; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment