Advertisement
STANAANDREY

builder design pattern

Sep 12th, 2023
770
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.50 KB | None | 0 0
  1.  
  2. class Burger {
  3.     private String cheese, patty, buns;
  4.     public Burger() {}
  5.  
  6.     public void setCheese(String cheese) {
  7.         this.cheese = cheese;
  8.     }
  9.  
  10.     public void setPatty(String patty) {
  11.         this.patty = patty;
  12.     }
  13.  
  14.     public void setBuns(String buns) {
  15.         this.buns = buns;
  16.     }
  17.  
  18.     @Override
  19.     public String toString() {
  20.         return "Burger{" +
  21.                 "cheese='" + cheese + '\'' +
  22.                 ", patty='" + patty + '\'' +
  23.                 ", buns='" + buns + '\'' +
  24.                 '}';
  25.     }
  26. }
  27.  
  28. class BurgerBuilder {
  29.     private Burger burger;
  30.  
  31.     public BurgerBuilder() {
  32.         burger = new Burger();
  33.     }
  34.  
  35.     public BurgerBuilder addBuns(String bunStyle) {
  36.         burger.setBuns(bunStyle);
  37.         return this;
  38.     }
  39.     public BurgerBuilder addCheese(String cheeseStyle) {
  40.         burger.setCheese(cheeseStyle);
  41.         return this;
  42.     }
  43.     public BurgerBuilder addPatty(String patty) {
  44.         burger.setPatty(patty);
  45.         return this;
  46.     }
  47.  
  48.     public Burger build() {
  49.         return this.burger;
  50.     }
  51. }
  52.  
  53. public class Main {
  54.  
  55.     public static void main(String[] args) {
  56.         var burgerBuilder = new BurgerBuilder();
  57.         var burger = burgerBuilder
  58.                                 .addBuns("sesame")
  59.                                 .addPatty("fish-patty")
  60.                                 .addCheese("chedar")
  61.                                 .build();
  62.         System.out.println(burger);
  63.     }
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement