不幸的是我被困在这里。
考虑以下基本例子:
interface ChargeInterface
{
public function charge($amount);
}
class BraintreeCharge implements ChargeInterface
{
public function charge($amount)
{
// braintree logic here
}
}
class StripeCharge implements ChargeInterface
{
public function charge($amount)
{
// stripe logic here
}
}
因此,有一个用于为付款方式收费的界面,在这个例子中,有两个实现该界面的具体类。
我希望能够决定运行时应该使用哪种实现。所以我想我会通过自定义工厂类来实现这个目标:
class PaymentFactory
{
public static $implementation;
public static function charge()
{
return $implementation::charge();
}
}
class StripeFactory
{
public static function charge()
{
return new StripeCharge();
}
}
class BraintreeFactory
{
public static function charge()
{
return new BraintreeCharge();
}
}
我可以使用工厂:
PaymentFactory::$implemention = StripeFactory::class;
$payments = PaymentFactory::charge();
$payments->charge(100);
另一个想法是使用基于单例的逻辑:
class PaymentFactory extends Singleton
{
protected $implementation;
// Singleton logic missing in this example
public function useImplementation($class)
{
$this->implementation = $class;
}
public function getImplementation()
{
return $this->implementation;
}
public static function charge()
{
$instance = self::getInstance();
return new $instance->getImplementation();
}
}
稍后......
PaymentFactory::getInstance()->useImplementation(StripeCharge::class);
$payments = PaymentFactory::charge();
$payments->charge(100);
您对这里的最佳做法有什么建议吗? 我认为我赞成第一个,因为真正的实现不仅包括每个包一个类,如示例中所述。 在我看来,这将是更清洁的方式。