使用界面实现开闭原则(SOLID)
Achieve Open-Closed Principle (SOLID) Using Interface
我有多种付款方式(Stripe、Paypal、PayUMoney 等)。我想为每种支付类型创建单独的 class 和一个 支付接口 以由 class 像这样
实现
interface PaymentInterface {
public function payment($params);
}
class Stripe implements PaymentInterface {
public function payment($params) { ... }
}
class Paypal implements PaymentInterface {
public function payment($params) { ... }
}
从我的主要class,我想使用付款方式。我会将付款数据发送到我的主要方法,并希望动态检测付款方式。
class PaymentModule {
public function confirmPayment(Request $request){
// create an object of the payment class
// $obj = new PaymentTypeClass **(Problem is here)**
// $obj->payment($params)
}
}
我的问题是,如何动态创建相关支付 class/object 并从 main 方法调用 payment() 方法?
如果我有条件地创建对象,那么我就违反了开闭原则。因为,我正在使用 If ... else 检查支付类型,然后创建对象并调用 payment() 这可能需要进一步修改.
If I create object conditionally then I am violating Open-Closed principle. Because, I am checking the payment type using If ... else then creating the object and calling the payment() which will may need further modification.
您的部分代码最终将不得不接受用户输入并决定使用哪种支付方式。这通常是使用 factory object 完成的,它可能使用 if-else 或映射或其他一些方式来返回正确的对象,这就是工厂的 "single responsibility"。
我有多种付款方式(Stripe、Paypal、PayUMoney 等)。我想为每种支付类型创建单独的 class 和一个 支付接口 以由 class 像这样
实现interface PaymentInterface {
public function payment($params);
}
class Stripe implements PaymentInterface {
public function payment($params) { ... }
}
class Paypal implements PaymentInterface {
public function payment($params) { ... }
}
从我的主要class,我想使用付款方式。我会将付款数据发送到我的主要方法,并希望动态检测付款方式。
class PaymentModule {
public function confirmPayment(Request $request){
// create an object of the payment class
// $obj = new PaymentTypeClass **(Problem is here)**
// $obj->payment($params)
}
}
我的问题是,如何动态创建相关支付 class/object 并从 main 方法调用 payment() 方法?
如果我有条件地创建对象,那么我就违反了开闭原则。因为,我正在使用 If ... else 检查支付类型,然后创建对象并调用 payment() 这可能需要进一步修改.
If I create object conditionally then I am violating Open-Closed principle. Because, I am checking the payment type using If ... else then creating the object and calling the payment() which will may need further modification.
您的部分代码最终将不得不接受用户输入并决定使用哪种支付方式。这通常是使用 factory object 完成的,它可能使用 if-else 或映射或其他一些方式来返回正确的对象,这就是工厂的 "single responsibility"。