-
-
Save gunhansancar/af2b1fee0b5613ccf40e to your computer and use it in GitHub Desktop.
Builder Pattern Example with Pizza
This file contains 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
package com.gunhansancar.android.pizza.builder; | |
import java.util.ArrayList; | |
import java.util.List; | |
/** | |
* Created by Günhan on 10.03.2016. | |
*/ | |
public class Pizza { | |
private final List<Topping> toppings; | |
private final String size; | |
private final String souce; | |
private Pizza(Builder builder) { | |
this.size = builder.size; | |
this.souce = builder.souce; | |
this.toppings = builder.toppings; | |
} | |
public String description() { | |
StringBuilder sb = new StringBuilder(); | |
sb.append(String.format("This is a %s sized pizza with %s souce.", size, souce)); | |
if (toppings != null) { | |
sb.append("\nIt contains;"); | |
for (Topping topping : toppings) { | |
sb.append(String.format("\n%s", topping.description())); | |
} | |
} | |
return sb.toString(); | |
} | |
private static class Topping { | |
private final String name; | |
private boolean cooked; | |
public Topping(String name) { | |
this.name = name; | |
} | |
public void setCooked(boolean cooked) { | |
this.cooked = cooked; | |
} | |
public String description() { | |
return String.format("%s%s", cooked ? "Cooked " : "", name); | |
} | |
} | |
public static class Builder { | |
private List<Topping> toppings; | |
private String size; | |
private String souce; | |
public Builder(String size) { | |
this.size = size; | |
} | |
public Builder with(String name) { | |
if (toppings == null) { | |
toppings = new ArrayList<>(); | |
} | |
toppings.add(new Topping(name)); | |
return this; | |
} | |
public Builder cooked() { | |
if (toppings != null && toppings.size() > 0) { | |
Topping topping = toppings.get(toppings.size() - 1); | |
topping.setCooked(true); | |
} | |
return this; | |
} | |
public Builder souce(String souce) { | |
this.souce = souce; | |
return this; | |
} | |
public Pizza build() { | |
return new Pizza(this); | |
} | |
} | |
public static void main(String[] args) { | |
Pizza pizza = new Pizza.Builder("medium") | |
.souce("tomato") | |
.with("Onion") | |
.with("Sausage").cooked() | |
.with("Mozzarella") | |
.build(); | |
System.out.println(pizza.description()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment