"concrete implementation"依赖-6ren"> "concrete implementation"依赖-我有一个“提供者工厂”,它创建具体提供者的实现。要创建正确的实现,除其他参数外,它还需要 typeId。问题是为了将正确的 typeId 传递给工厂,我需要验证并在必要时更改它。为了做到这一点,除其他-6ren">
gpt4 book ai didi

php - 移除 "factory"<->"concrete implementation"依赖

转载 作者:搜寻专家 更新时间:2023-10-31 21:30:35 26 4
gpt4 key购买 nike

我有一个“提供者工厂”,它创建具体提供者的实现。要创建正确的实现,除其他参数外,它还需要 typeId。问题是为了将正确的 typeId 传递给工厂,我需要验证并在必要时更改它。为了做到这一点,除其他参数外,我需要一个特定提供者的实例。这就是问题所在 - 提供者应该是单例(我真的不想让它成为带有大写 S 的单例),因为它查询数据库并将结果缓存在内部属性中。

所以我的问题是 - 是否有更合适的模式或其他方法来实现类似的目标?

class ProviderFactory
{

public function createProvider($typeId)
{
if ($typeId == 2) {
return new Provider2($arg1, $arg5);
} elseif ($typeId == 4) {
return new Provider4();
} else {
return new ProviderDefault($typeId, $arg1, $arg2, $arg3, $arg4);
}
}
}


interface ProviderInterface
{
public function getCost();
}

class ProviderDefault implements ProviderInterface
{
public function __construct($arg1, $arg2, $arg3, $arg4) {}

public function getCost() { /*implementation*/ }
}

class Provider2 implements ProviderInterface
{
public function __construct($arg1, $arg5) {}

public function getCost() { /*implementation*/ }
}

// this call can be implemented with the following condition
// if ($typeId == 2) {
// if ($provider2->getCost() !== null)
// $typeId = 1;
// }
//
$typeId = fixAndValidateTypeId($typeId, new Provider2($arg1, $arg5));


$factory = new ProviderFactory();
$provider = $factory->createProvider($typeId);

最佳答案

我建议您在 ProviderFactory 中实现 ChainOfResponsibility 模式,这样您就不需要在每次添加新 Provider 或更改逻辑时都修改 ProviderFactory。您只需添加 RegisterProvider(IProvider provider) 方法以在链中添加提供者,然后循环遍历此提供者链,调用每个 IProvider 的 bool:DoesProviderSuit(int typeId, out IProvider)。

希望你捕获一个想法,祝​​你好运!

关于php - 移除 "factory"<->"concrete implementation"依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30438001/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com