Паттерн "Проста фабрика"
Проста фабрика просто генерить екземпляр для клієнта без представлення якоїн-небудь логіки самого екземпляра
Коли використовувати?
Коли створення об'єкта має на увазі якусь логіку, а не просто кілька присвоювань, то має сенс делегувати завдання виділеній фабриці, а не повторювати всюди один і той же код.
PHP
interface Door
{
public function getWidth(): float;
public function getHeight(): float;
}
class WoodenDoor implements Door
{
protected $width;
protected $height;
public function __construct(float $width, float $height)
{
$this->width = $width;
$this->height = $height;
}
public function getWidth(): float
{
return $this->width;
}
public function getHeight(): float
{
return $this->height;
}
}
Тепер створим фабрику
class DoorFactory
{
public static function makeDoor($width, $height): Door
{
return new WoodenDoor($width, $height);
}
}
Використання:
$door = DoorFactory:makeDoor(100, 200);
echo 'Width: ' . $door->getWidth();
echo 'Height: ' . $door->getHeight();
JavaScript
class User {
constructor(name, age, role) {
this.name = name;
this.age = role;
this.role = role;
}
}
class UserFactory {
static createUserAdmin(name, age) {
return new User(name, age, 'admin');
}
static creteUserModerator(name, age) {
return new User(name, age, 'moderator');
}
}
let admin = UserFactory.createUserAdmin('Mike', 43);
2019-05-12 12:43:10