Factory Methodパターン
インスタンスの作り方をスーパークラス側で定める。
具体的な肉付けはサブクラス側で行う。
Product.php
abstract class Product { abstract public function use(): void; }
Factory.php
abstract class Factory { final public function create(string $owner): Product { $p = $this->createProduct($owner); $this->registerProduct($p); return $p; } abstract protected function createProduct(string $owner): Product; abstract protected function registerProduct(Product $product): void; }
IDCard.php
class IDCard extends Product { private $owner; function __construct(string $owner) { echo $owner."のカードをつくります。\n"; $this->owner = $owner; } public function use(): void { echo $this->owner."のカードを使います。\n"; } public function getOwner(): string { return $this->owner; } }
IDCardFactory.php
class IDCardFactory extends Factory { private $owners = []; protected function createProduct(string $owner): Product { return new IDCard($owner); } protected function registerProduct(Product $product): void { $owners[] = $product->getOwner(); } public function getOwners(): array { return $owners; } }
Main.php
require "../autoload.php"; $factory = new IDCardFactory(); $card1 = $factory->create("佐藤"); $card2 = $factory->create("鈴木"); $card1->use(); $card2->use();
実行結果
佐藤のカードをつくります。 鈴木のカードをつくります。 佐藤のカードを使います。 鈴木のカードを使います。
autoload.php
function autoload($className){ require './'.$className.'.php'; } spl_autoload_register('autoload');