jorge9983

Clase Pizza Patron Builder PHP

Jul 20th, 2025 (edited)
269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.62 KB | None | 0 0
  1. <?php
  2.  
  3. class Pizza {
  4.     private $tamaño;
  5.     private $masa;
  6.     private $orillaConQueso;
  7.     private $ingredientes;
  8.  
  9.     private function __construct($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.     public static function builder() {
  17.         return new PizzaBuilder();
  18.     }
  19.  
  20.     public function mostrar() {
  21.         echo "Pizza: $this->tamaño, $this->masa, orilla con queso: " . ($this->orillaConQueso ? "sí" : "no") . ", ingredientes: $this->ingredientes\n";
  22.     }
  23.  
  24.     // Clase Builder
  25.     class PizzaBuilder {
  26.         public $tamaño;
  27.         public $masa;
  28.         public $orillaConQueso = false;
  29.         public $ingredientes;
  30.  
  31.         public function tamaño($tamaño) {
  32.             $this->tamaño = $tamaño;
  33.             return $this;
  34.         }
  35.  
  36.         public function masa($masa) {
  37.             $this->masa = $masa;
  38.             return $this;
  39.         }
  40.  
  41.         public function orillaConQueso($orillaConQueso) {
  42.             $this->orillaConQueso = $orillaConQueso;
  43.             return $this;
  44.         }
  45.  
  46.         public function ingredientes($ingredientes) {
  47.             $this->ingredientes = $ingredientes;
  48.             return $this;
  49.         }
  50.  
  51.         public function build() {
  52.             return new Pizza($this);
  53.         }
  54.     }
  55. }
  56.  
  57. // USO:
  58. $pizza = Pizza::builder()
  59.     ->tamaño("Mediana")
  60.     ->masa("Gruesa")
  61.     ->orillaConQueso(true)
  62.     ->ingredientes("Jamón, Aceitunas")
  63.     ->build();
  64.  
  65. $pizza->mostrar();
  66. ?>
  67.  
Advertisement
Add Comment
Please, Sign In to add comment