Skip to content

Commit 1bb2cf0

Browse files
authored
Merge pull request mouredev#4267 from miguelex/main
#24 - php
2 parents 9f29e4d + a8af7f9 commit 1bb2cf0

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
<?php
2+
3+
4+
interface Vehicle {
5+
public function wheels();
6+
}
7+
8+
class Car implements Vehicle {
9+
public function wheels() {
10+
return 4;
11+
}
12+
}
13+
14+
class Bike implements Vehicle {
15+
public function wheels() {
16+
return 2;
17+
}
18+
}
19+
20+
class VehicleDecorator implements Vehicle {
21+
protected $vehicle;
22+
23+
public function __construct(Vehicle $vehicle) {
24+
$this->vehicle = $vehicle;
25+
}
26+
27+
public function wheels() {
28+
return $this->vehicle->wheels();
29+
}
30+
}
31+
32+
// Vamos a usar el patron decorador para definir ahora un tipo especial de coche que sol otien 2 puertas
33+
class Coupe extends VehicleDecorator {
34+
public function doors() {
35+
return 2;
36+
}
37+
}
38+
39+
$car = new Car();
40+
$bike = new Bike();
41+
echo "Un coche tiene ".$car->wheels()." ruedas\n";
42+
echo "Una bicicleta tiene ".$bike->wheels(). " ruedas\n";
43+
$carWithDoors = new Coupe($car);
44+
echo "Prueba de uso de decorador\n";
45+
echo "Un coche modelo Coupe tiene ".$carWithDoors->wheels(). " ruedas pero solo tiene ".$carWithDoors->doors()." puertas\n";
46+
47+
// Ejercicio extra
48+
49+
echo "\n\nEjercicio extra\n";
50+
51+
52+
interface Funcion {
53+
public function ejecutar();
54+
}
55+
56+
class Suma implements Funcion {
57+
private $a;
58+
private $b;
59+
60+
public function __construct($a, $b) {
61+
$this->a = $a;
62+
$this->b = $b;
63+
}
64+
65+
public function ejecutar() {
66+
return $this->a + $this->b;
67+
}
68+
}
69+
70+
class ContadorDeLlamadas implements Funcion {
71+
private $funcion;
72+
private static $contador = 0;
73+
74+
public function __construct(Funcion $funcion) {
75+
$this->funcion = $funcion;
76+
}
77+
78+
public function ejecutar() {
79+
self::$contador++;
80+
echo "La función ha sido llamada " . self::$contador . " veces.\n";
81+
return $this->funcion->ejecutar();
82+
}
83+
}
84+
85+
$suma = new Suma(2, 2);
86+
$sumaContada = new ContadorDeLlamadas($suma);
87+
88+
echo $sumaContada->ejecutar() . "\n";
89+
echo $sumaContada->ejecutar() . "\n";
90+
echo $sumaContada->ejecutar() . "\n";
91+
92+
93+

0 commit comments

Comments
 (0)