我正在一个项目中,我们正在整个代码库中创建许多对象。
因此,对于某些对象,我们决定使用工厂来控制创建对象及其所有依赖项的过程。这是我们正在尝试做的一个例子:
class CreateBranchFactory implements CreateBranchInterface {
private $branch;
public function __construct() {
$this->branch = new Branch();
$this->branch->scenario = 'create';
}
public function createBranch($branchForm) {
$this->branch->attributes = $branchForm->attributes;
//Example of all the things that I need to do after creating my object
$this->setOfficialNameAndPrinterName($branchForm->official_name, $branchForm->printer_name, $branchForm->name);
$this->createDependencies1();
$this->someOtherFunction();
return $this->branch;
}
public function setOfficialNameAndPrinterName($offName, $printerName, $branchName) {
$this->branch->official_name = $offName ?? $branchName;
$this->branch->printer_name = $printerName ?? $branchName;
$this->branch->save();
}
public function createDependencies1() {
}
为了拥有适当的合同,我为此创建了一个接口。该接口指定应定义的功能
interface CreateBranchInterface {
public function setOfficialNameAndPrinterName(String $offName, String $printerName, String $branchName);
public function createDependencies1();
}
我的问题是,合同规定了应定义的所有功能,但没有控制应调用的功能。我可以使用任何设计模式来确保调用这些功能吗?
答案 0 :(得分:2)
您不能通过使用接口来创建此类合同-接口指定了哪些方法以及如何调用。调用所有这些方法是实现的一部分,接口无法提供。您需要使用实现创建抽象类,并使用final
关键字禁止覆盖它:
abstract class CreateBranch {
abstract protected function getBranch(): Branch;
final public function createBranch($branchForm) {
$this->getBranch()->attributes = $branchForm->attributes;
//Example of all the things that I need to do after creating my object
$this->setOfficialNameAndPrinterName($branchForm->official_name, $branchForm->printer_name, $branchForm->name);
$this->createDependencies1();
$this->someOtherFunction();
return $this->getBranch();
}
abstract public function setOfficialNameAndPrinterName(String $offName, String $printerName, String $branchName);
abstract public function createDependencies1();
abstract public function someOtherFunction();
}