工廠模式(Factory Pattern)是一種創建型設計模式,它提供了一種在不指定具體類的情況下創建對象的方法。結合其他設計模式,可以更好地解決特定問題并提高代碼的可維護性和可擴展性。以下是一些建議:
class SingletonFactory {
private static $instance;
private function __construct() {}
public static function getInstance() {
if (null === self::$instance) {
self::$instance = new Singleton();
}
return self::$instance;
}
}
class Product {
private $partA;
private $partB;
private function __construct($partA, $partB) {
$this->partA = $partA;
$this->partB = $partB;
}
public static function create($partA, $partB) {
return new Product($partA, $partB);
}
}
class Builder {
private $product = null;
public function setPartA($partA) {
$this->product->setPartA($partA);
return $this;
}
public function setPartB($partB) {
$this->product->setPartB($partB);
return $this;
}
public function build() {
return $this->product;
}
}
class Target {
public function request() {
throw new Exception("Request not supported.");
}
}
class Adaptee {
public function specificRequest() {
return "Specific request handled.";
}
}
class Adapter implements Target {
private $adaptee;
public function __construct(Adaptee $adaptee) {
$this->adaptee = $adaptee;
}
public function request() {
return $this->adaptee->specificRequest();
}
}
class Factory {
public static function createAdapter() {
$adaptee = new Adaptee();
return new Adapter($adaptee);
}
}
這些結合方式可以根據實際需求和項目結構進行調整。工廠模式與其他設計模式的結合有助于提高代碼的可維護性、可擴展性和可重用性。