jorge9983

Clase Pizza Patron Builder

Jul 20th, 2025 (edited)
335
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.79 KB | None | 0 0
  1. // Clase Producto
  2. public class Pizza {
  3.     private String tamaño;
  4.     private String masa;
  5.     private boolean orillaConQueso;
  6.     private String ingredientes;
  7.  
  8.     // Constructor privado: solo se puede construir desde el Builder
  9.     private Pizza(Builder builder) {
  10.         this.tamaño = builder.tamaño;
  11.         this.masa = builder.masa;
  12.         this.orillaConQueso = builder.orillaConQueso;
  13.         this.ingredientes = builder.ingredientes;
  14.     }
  15.  
  16.     // Clase interna Builder
  17.     public static class Builder {
  18.         private String tamaño;
  19.         private String masa;
  20.         private boolean orillaConQueso;
  21.         private String ingredientes;
  22.  
  23.         public Builder tamaño(String tamaño) {
  24.             this.tamaño = tamaño;
  25.             return this;
  26.         }
  27.  
  28.         public Builder masa(String masa) {
  29.             this.masa = masa;
  30.             return this;
  31.         }
  32.  
  33.         public Builder orillaConQueso(boolean orillaConQueso) {
  34.             this.orillaConQueso = orillaConQueso;
  35.             return this;
  36.         }
  37.  
  38.         public Builder ingredientes(String ingredientes) {
  39.             this.ingredientes = ingredientes;
  40.             return this;
  41.         }
  42.  
  43.         public Pizza build() {
  44.             return new Pizza(this);
  45.         }
  46.     }
  47.  
  48.     public void mostrar() {
  49.         System.out.println("Pizza: " + tamaño + ", " + masa + ", orilla con queso: " + orillaConQueso + ", ingredientes: " + ingredientes);
  50.     }
  51. }
  52.  
  53. // USO:
  54. public class Main {
  55.     public static void main(String[] args) {
  56.         Pizza pizza = new Pizza.Builder()
  57.             .tamaño("Grande")
  58.             .masa("Delgada")
  59.             .orillaConQueso(true)
  60.             .ingredientes("Queso, Pepperoni, Champiñones")
  61.             .build();
  62.  
  63.         pizza.mostrar();
  64.     }
  65. }
  66.  
Advertisement
Add Comment
Please, Sign In to add comment