【发布时间】:2018-02-11 13:47:23
【问题描述】:
我正在学习设计模式概念,并且还想使用适当的设计模式在我的项目中实施支付模块。因此,为此我创建了一些示例代码。
目前我有两个具体的付款方式PayPal 和Credit Card。但具体的实现将在项目中进一步添加。
支付服务
public interface IPaymentService
{
void MakePayment<T>(T type) where T : class;
}
信用卡和 Pay Pal 服务
public class CreditCardPayment : IPaymentService
{
public void MakePayment<T>(T type) where T : class
{
var creditCardModel = (CreditCardModel)(object)type;
//Implementation CreditCardPayment
}
}
class PayPalPayment : IPaymentService
{
public void MakePayment<T>(T type) where T : class
{
var payPalModel = (PayPalModel)(object)type;
//Further Implementation will goes here
}
}
客户端代码实现
var obj = GetPaymentOption(payType);
obj.MakePayment<PayPalModel>(payPalModel);
获取付款选项
private static IPaymentService GetPaymentOption(PaymentType paymentType)
{
IPaymentService paymentService = null;
switch (paymentType)
{
case PaymentType.PayPalPayment:
paymentService = new PayPalPayment();
break;
case PaymentType.CreditCardPayment:
paymentService = new CreditCardPayment();
break;
default:
break;
}
return paymentService;
}
我想用策略设计模式来实现这个模块,但我偏离了策略,最终这样做了。
这是创建支付模块的正确方法吗?有没有更好的方法来解决这种情况。这是一种设计模式吗?
编辑:
客户代码:
static void Main(string[] args)
{
PaymentStrategy paymentStrategy = null;
paymentStrategy = new PaymentStrategy(GetPaymentOption((PaymentType)1));
paymentStrategy.Pay<PayPalModel>(new PayPalModel() { UserName = "", Password = "" });
paymentStrategy = new PaymentStrategy(GetPaymentOption((PaymentType)2));
paymentStrategy.Pay<CreditCardModel>(
new CreditCardModel()
{
CardHolderName = "Aakash"
});
Console.ReadLine();
}
策略:
public class PaymentStrategy
{
private readonly IPaymentService paymentService;
public PaymentStrategy(IPaymentService paymentService)
{
this.paymentService = paymentService;
}
public void Pay<T>(T type) where T : class
{
paymentService.MakePayment(type);
}
}
此更新是否与策略模式内联?
【问题讨论】:
-
这看起来更像是代码审查,也是基于意见的。
-
@Nkosi 你的意思是问题不应该在这里?
-
如果您以 CreditCardPayment 的形式实现了 IPaymentService 的具体实现,那么将 MakePayment 耦合到更具体的类型是否没有意义?您可以使用 IPaymentService
,其中 T 是用于 MakePayment 的类型。 -
接下来,让 CreditCard 和 PayPal 模型继承的 IPayModel 接口以及 IPaymentService 上的 MakePayment 方法采用 IPayModel 作为参数可能是有意义的
-
CreditCard 和 PayPal 模型具有不同的属性,它们没有任何共同的属性。既然他们没有共享任何共同的东西,那么从 IPayModel 接口继承类是否有意义?
标签: c# design-patterns