如何使用工厂和依赖注入模式决定调用哪个类?

问题描述

我在项目的最低层(主层)使用工厂模式来注入依赖项,所以我有这样的东西

class ReservePaymentFactory {

    public function execute() {

        $pagseguroAdapter = new PagSeguroAdapter();

        $paymentRepository = new PaymentRepository();  

        $reservePaymentService = new ReservePaymentService(
            $pagseguroAdapter,$paymentRepository,);

        $reservePaymentConsumer = new ReservePaymentConsumer($reservePaymentService);

        return $reservePaymentConsumer;
    }
}

class ReservePaymentService implements ReservePayment {

    private $paymentGateway;
    private $savePaymentDb;

    public function __construct(
        PaymentGateway $paymentGateway,SavePaymentDB $savePaymentDb,) {
        $this->paymentGateway = $paymentGateway;
        $this->savePaymentDb = $savePaymentDb;
    }

    public function execute(Card $card,string $hash) : bool
    {
        $paymentValidator = $this->paymentGateway->reservePayment($card);
    }
}

interface PaymentGateway  {
    public function reservePayment(Card $card) : ?string;
}

PagSeguroAdapter 类实现 PaymentGateway。

我的 ReservePaymentService 类依赖于由 PagSeguroAdapter(网关)实现的 PaymentGateway 接口。现在,我需要添加一个新网关并根据业务规则决定使用哪个网关。

我该怎么做?我的 ReservePaymentService 现在需要接收两个网关并决定调用哪个,但 ReservePaymentService 依赖于接口,而不是具体的类。

在一些帖子中,我看到也许我可以使用策略模式,但老实说,我不知道该怎么做。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)