最全最简单的PHP工厂模式以支付为例

详细的注解
整理了放在这里 方便 CTRL+V

<?php  
  
// 定义PaymentMethod接口  
interface PaymentMethod {  
    public function processPayment();  
} 
// 实现PaymentBase类,该类为基类实现接口检测  
abstract class PaymentBase implements PaymentMethod{
	protected $config;
	protected $order;
  
    public function __construct($config) {  
        $this->config = $config;  
    }  
	public function __call($method,$args){
		if (!method_exists($this, $method)) { 
			$className = get_class($this);
            throw new Exception("Class '$className' Method '$method' does not exist.");  
        }
        // 如果方法存在,则调用该方法并传递参数  
        return call_user_func_array([$this, $method], $args);  
	}
	public function __set($name, $val){
		$this->$name = $val;
	}
} 
  
// 实现CreditCardPayment类,该类实现PaymentMethod接口  
class CreditCardPayment extends PaymentBase  {  
   
  
    public function processPayment() {  
        // 使用初始化时传入的配置文件进行信用卡支付操作...  
        echo "处理信用卡支付...".json_encode($this->config);  
    }  
}  
  
// 实现PayPalPayment类,该类实现PaymentMethod接口  
class PayPalPayment extends PaymentBase {  
  
    public function processPayment() {  
        // 使用初始化时传入的配置文件进行PayPal支付操作... 
        echo "处理PayPal支付...".json_encode($this->config).json_encode($this->order);  
    }  
}  
  
// 定义PaymentFactory类,用于创建支付方式对象  
class PaymentFactory {  
    // 创建指定类型的支付方式对象  
    public static function createPaymentMethod($type,  $config = []) {  
        // 检查支付方式类型是否存在对应的支付方式类  
        if (!class_exists($type)) {  
            throw new Exception("无效的支付方式类型。无效的支付类。");  
        }  
          
        // 获取支付方式类的反射对象  
        $paymentClass = new \ReflectionClass($type);  
          
        // 创建支付方式对象并使用传入的配置文件进行初始化  
        $payment = $paymentClass->newInstance($config); // 使用传入的配置文件进行初始化  
        return $payment; // 返回初始化的支付方式对象给调用者使用
    }  
    
}  
  
  
// 使用示例  
try {  
    // 创建信用卡支付方式对象,并调用processPayment方法,不传入配置文件,由工厂方法自动加载配置文件进行初始化。  
    $creditCardPayment = PaymentFactory::createPaymentMethod('CreditCardPayment',['name'=>'pay1']);  
    // 执行信用卡支付操作,输出: 处理信用卡支付...  
    $creditCardPayment->processPayment(); // 输出: 处理信用卡支付...  
      
    // 创建PayPal支付方式对象,并调用processPayment方法,不传入配置文件,由工厂方法自动加载配置文件进行初始化。  
    $payPalPayment = PaymentFactory::createPaymentMethod('PayPalPayment',['name'=>'pay2']);  
    $payPalPayment->order=['id'=>'abc'];
    // 执行PayPal支付操作,输出: 处理PayPal支付...  
    $payPalPayment->processPayment(); // 输出: 处理PayPal支付...  
} catch (Exception $e) {  
    echo "发生错误: " . $e->getMessage();  
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

漫游游²º¹²

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值