LoginSignup
26
22

More than 5 years have passed since last update.

PHPでFactoryパターン

Posted at

もはや知らずしらずのうちに使っていてもおかしくないほど多用されているファクトリーパターン。私もようやくソースコードの中でいきなりnew XXXをすることに気持ち悪さを覚えてくるようになりましたが、まさに気持ち悪い理由の解決策がファクトリーパターンです。

気持ち悪い理由は明確で、ソースコードのあちこちでnew XXXをするとXXX内の設計が変わったときに、すべてのnew XXXを調べだしていちいち変更しなくてはいけないからです。

そのためnew XXXをする部分を1箇所(これがファクトリー、工場と呼ばれる所以ですが)にまとめたものがFactoryパターンです。

Automobile.php
class Automoblie
{
   $vehicleMake;
   $vehicleModel;

   public function __construct($make, $model)
   {
      $this->vehicleMake = $make;
      $this->vehicleModel = $model;
   }

   public getName()
   {
      return $vehicleMake . ' ' . $vehicleModel; 
   } 
}

こんな自動車の設計書があったとします。この自動車を生成する工場をつくります。

AutomobileFactory.php
public static function create($make, $model)
{
   return new Automobile($make, $model);
}

こんなかんじですね。newが一箇所にまとまっているため、何か変更があった場合もFactoryに変更を加えればokです。
実際の呼び出しはこんなかんじ。

index.php
$automobile = AutomobileFactory::create('ブガッティ''ヴァイロン');
echo $automobile->getName();  // ブガッティ ヴァイロン

オブジェクト作成の初期化が煩雑になったときもFactoryパターンをつかっていると、一箇所にまとまるので楽、という特典もあります。

26
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
22