
interface PaymentInterface {
public function createOrder(float $amount): string;
public function pay(string $orderId): bool;
}
// 支付宝支付
class Alipay implements PaymentInterface {
public function createOrder(float $amount): string {
return "支付宝订单:" . uniqid();
}
public function pay(string $orderId): bool {
echo "支付宝支付订单 {$orderId} 成功\n";
return true;
}
}
// 微信支付
class WechatPay implements PaymentInterface {
public function createOrder(float $amount): string {
return "微信订单:" . uniqid();
}
public function pay(string $orderId): bool {
echo "微信支付订单 {$orderId} 成功\n";
return true;
}
}
class PaymentFactory {
// 静态工厂方法,根据类型创建对应支付对象
public static function createPayment(string $type): PaymentInterface {
switch ($type) {
case 'alipay':
return new Alipay();
case 'wechat':
return new WechatPay();
default:
throw new InvalidArgumentException("不支持的支付方式:{$type}");
}
}
}
// 获取支付宝支付对象
$alipay = PaymentFactory::createPayment('alipay');
$orderId = $alipay->createOrder(99.9);
$alipay->pay($orderId);
// 获取微信支付对象
$wechatPay = PaymentFactory::createPayment('wechat');
$orderId2 = $wechatPay->createOrder(199.9);
$wechatPay->pay($orderId2);
interface PaymentFactoryInterface {
public function createPayment(): PaymentInterface;
}
class AlipayFactory implements PaymentFactoryInterface {
private $appId;
private $privateKey;
public function __construct(string $appId, string $privateKey) {
$this->appId = $appId;
$this->privateKey = $privateKey;
}
public function createPayment(): PaymentInterface {
// 初始化支付宝配置
return new Alipay($this->appId, $this->privateKey);
}
}
class WechatPayFactory implements PaymentFactoryInterface {
private $mchId;
private $apiKey;
public function __construct(string $mchId, string $apiKey) {
$this->mchId = $mchId;
$this->apiKey = $apiKey;
}
public function createPayment(): PaymentInterface {
// 初始化微信支付配置
return new WechatPay($this->mchId, $this->apiKey);
}
}
// 支付宝工厂(带配置)
$alipayFactory = new AlipayFactory('2021000000000000', '私钥内容');
$alipay = $alipayFactory->createPayment();
// 微信支付工厂(带配置)
$wechatFactory = new WechatPayFactory('1600000000', 'API密钥');
$wechatPay = $wechatFactory->createPayment();