Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Builder pattern
package com.app.designPatterns.builder1;
public class BuilderApp {
public static void main(String[] args) {
Phone iphone = new PhoneBuilder().setModel("Apple").setOs("IOS").buildPhone();
System.out.println(iphone);
Phone androidPhone = new PhoneBuilder().setModel("Nokia").setOs("Android").setCamera("32MP").buildPhone();
System.out.println(androidPhone);
}
}
package com.app.designPatterns.builder1;
public class Phone {
private String model;
private String os;
private Integer price;
private String camera;
public Phone(String model, String os, Integer price, String camera) {
super();
this.model = model;
this.os = os;
this.price = price;
this.camera = camera;
}
@Override
public String toString() {
return "Phone{" +
"model='" + model + '\'' +
", os='" + os + '\'' +
", price=" + price +
", camera='" + camera + '\'' +
'}';
}
}
package com.app.designPatterns.builder1;
public class PhoneBuilder {
private String model;
private String os;
private Integer price;
private String camera;
public PhoneBuilder setModel(String model) {
this.model = model;
return this;
}
public PhoneBuilder setOs(String os) {
this.os = os;
return this;
}
public PhoneBuilder setPrice(Integer price) {
this.price = price;
return this;
}
public PhoneBuilder setCamera(String camera) {
this.camera = camera;
return this;
}
public Phone buildPhone() {
return new Phone(model, os, price, camera);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment