For teaching purposes, I Am trying to create a "real world and a bit useful" example of Abstract Factory using PHP.
Without no major deviation from the original Abstract Factory GOF definition, I would like to know how to improve this code in a way that be possible to add css cdn to the respective css framework without developer needs to manually do it.
The current code is:
<?php
interface Button {
public function render(string $text);
}
interface Range {
public function render(int $max, int $min = 0);
}
class BootstrapButton implements Button {
public function render(string $text) {
echo '<button type="button" class="btn btn-primary">'.$text.'</button>';
}
}
class MaterializeButton implements Button {
public function render(string $text) {
echo '<a class="waves-effect waves-light btn">'.$text.'</a>';
}
}
class BootstrapRange implements Range {
public function render(int $max, int $min = 0) {
echo '<input type="range" min="'.$min.'" max="'.$max.'" class="custom-range" />';
}
}
class MaterializeRange implements Range {
public function render(int $max, int $min = 0) {
echo '<input type="range" min="'.$min.'" max="'.$max.'"/>';
}
}
//Fábricas
abstract class UIFactory{
abstract function createButton(): Button;
abstract function createRange(): Range;
}
class UIBootstrapFactory extends UIFactory {
public function createButton(): \Button {
return new BootstrapButton();
}
public function createRange(): \Range {
return new BootstrapRange();
}
}
class UIMaterializeFactory extends UIFactory {
public function createButton(): \Button {
return new MaterializeButton();
}
public function createRange(): \Range {
return new MaterializeRange();
}
}
class UIFactoryProvider{
public static function get(string $name): UIFactory{
$class_name = 'UI'.ucfirst($name).'Factory';
if(is_subclass_of($class_name, UIFactory::class)){
return new $class_name();
}
throw new \UnexpectedValueException("Factory does not exist");
}
}
echo '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">';
//echo '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">';
$fabrica = UIFactoryProvider::get('materialize');
$button = $fabrica->createButton();
$range = $fabrica->createRange();
$button->render('teste');
echo "<br/>";
$range->render(10);
Aucun commentaire:
Enregistrer un commentaire