Skip to content

Instantly share code, notes, and snippets.

@isaacssemugenyi
Last active January 9, 2024 10:05
Show Gist options
  • Save isaacssemugenyi/5a9d340baedccff3f2a55b2350e03f33 to your computer and use it in GitHub Desktop.
Save isaacssemugenyi/5a9d340baedccff3f2a55b2350e03f33 to your computer and use it in GitHub Desktop.
package builder;
import java.util.ArrayList;
import java.util.List;
public class Car {
private String make;
private String name;
private String color;
private int model;
private List<String> countriesPresent = new ArrayList<>();
public void setMake(String make) {
this.make = make;
}
public void setName(String name) {
this.name = name;
}
public void setColor(String color) {
this.color = color;
}
public void setModel(int model) {
this.model = model;
}
public void setCountriesPresent(List<String> countriesPresent) {
this.countriesPresent = countriesPresent;
}
@Override
public String toString() {
return String.format(
"{ make = %s, name = %s, color = %s, model = %s , countriesPresent = %s }",
make,
name,
color,
model,
countriesPresent
);
}
public Car(String make, String name, String color, int model, List<String> countriesPresent) {
this.make = make;
this.name = name;
this.color = color;
this.model = model;
this.countriesPresent = countriesPresent;
}
public Car(){}
/**
* Builder code below
*/
private Car(Builder builder){
this.make = builder.make;
this.name = builder.name;
this.color = builder.color;
this.model = builder.model;
this.countriesPresent = builder.countriesPresent;
}
public static class Builder {
private String make;
private String name;
private String color;
private int model;
private List<String> countriesPresent = new ArrayList<>();
public Builder make(String make){
this.make = make;
return this;
}
public Builder name(String name){
this.name = name;
return this;
}
public Builder color(String color){
this.color = color;
return this;
}
public Builder model(int model){
this.model = model;
return this;
}
public Builder addCountry(String countriesPresent){
this.countriesPresent.add(countriesPresent);
return this;
}
public Car build(){
return new Car(this);
}
}
}
package builder;
import java.util.List;
public class Main {
public static void main(String[] args){
Car car1 = new Car();
car1.setMake("Tesla");
car1.setName("Model X");
car1.setModel(2020);
car1.setColor("Blue");
car1.setCountriesPresent(List.of("USA", "Germany", "China"));
System.out.println("No args constructor --> "+car1);
Car car2 = new Car("Toyota", "Fortuner", "Grey", 2021, List.of("India", "Kenya", "South Africa"));
System.out.println("All Args Constructor --> "+ car2);
// Builder execution
Car car3 = new Car.Builder()
.make("Ford")
.name("Mastunga")
.color("Red")
.model(2023)
.addCountry("Kenya")
.addCountry("Uganda")
.build();
System.out.println("Builder 1 --> "+ car3);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment