Factory 模式(參數化)-極簡範例

工廠模式,參數化,1 座工廠,多個產品

修改 Creator 抽象類,實例化時,方法 factoryMethod() 要傳入產品物件,而這個物件由 startFactory() 在用戶端執行時傳入

//工廠抽象類別
abstract class Creator
{
    protected abstract function factoryMethod(IProduct $product);
    
    public function startFactory($productNow)
    {
        $motoProduct = $productNow;
        $mfg = $this->factoryMethod($motoProduct);
        return $mfg;
    }
}

修改工廠類別,只需要一座工廠,方法 factoryMethod() 要傳入產品物件

// 1 座工廠,多個產品
class MotoFactory extends Creator
{
    private $moto;
    
    protected function factoryMethod(IProduct $product)
    {
        $this->moto = $product;
        return $this->moto->make();
    }
}

以下產品的介面和實作都沒有改變原先的程式碼

//產品公用介面
interface IProduct
{
    public function make();
}

//產品Car
class CarProduct implements IProduct
{
    private $mfgProduct;
    
    public function make()
    {
        $this->mfgProduct = "This is a Car.<br />";
        return $this->mfgProduct;
    }
}

//產品Jet
class JetProduct implements IProduct
{
    private $mfgProduct;
    
    public function make()
    {
        $this->mfgProduct = "This is a Jet.<br />";
        return $this->mfgProduct;
    }
}

修改用戶端,執行時要傳入產品參數

//用戶端
class Client
{
    //只要 1 座工廠
    private $someProductObject;
    
    public function __construct()
    {
        $this->someProductObject = new MotoFactory();
        //分別傳入 2 個產品物件
        echo $this->someProductObject->startFactory(new CarProduct());
        echo $this->someProductObject->startFactory(new JetProduct());
    }
}

$worker = new Client();

Browser結果
This is a Car.
This is a Jet.