Skip to content

Instantly share code, notes, and snippets.

@hamburghammer
Last active November 7, 2019 15:23
Show Gist options
  • Save hamburghammer/04ec65bf1516955ba81df07dc6d1ec59 to your computer and use it in GitHub Desktop.
Save hamburghammer/04ec65bf1516955ba81df07dc6d1ec59 to your computer and use it in GitHub Desktop.
Java Factory Pattern Example
public final class Main {
public static void main(String[...] args) {
Bar s = new Bar.Builder(new Object())
.withObject1(new Object())
.withObject2(new Object())
.withString("s").build();
Bar build = Bar.builder(new Object()).build();
}
private static class Bar {
private final String string;
private final Object object1;
private final Object object2;
private final Object object3;
private Bar(String string, Object object1, Object object2, Object object3) {
this.string = string;
this.object1 = object1;
this.object2 = object2;
this.object3 = object3;
}
public static Builder builder(Object o) {
return new Builder(o);
}
private static class Builder {
private Object object1 = new Double(1);
private Object object2;
private final Object object3;
private String string;
private Builder(Object object3) {
this.object3 = object3;
}
public Builder withString(String s) {
this.string = s;
return this;
}
public Builder withObject1(Object o) {
this.object1 = o;
return this;
}
public Builder withObject2(Object o) {
this.object2 = o;
return this;
}
public Bar build() {
return new Bar(string, object1, object2, object3);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment