工厂模式(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);
}
}
这些结合方式可以根据实际需求和项目结构进行调整。工厂模式与其他设计模式的结合有助于提高代码的可维护性、可扩展性和可重用性。