【发布时间】:2017-03-19 06:19:03
【问题描述】:
有一个接口 IRule,它有一个方法 Validate() 和几个派生类,它们实现了这个方法。类具有不同的 ctors(类型和参数数量)。此外,还有一个名为 IPaymentProcessor 的核心接口,它必须验证所有现有规则。 我目前的任务是实现像工厂或容器这样的高级抽象,理想情况下创建具有不同构造函数的所有规则,然后将它们作为 IEnumerable 返回以迭代并应用每个规则进行卡验证。
是否可以使用 Ninject 或 .NET 中的任何其他基于反射的库来完成任务? (自动夹具、起订量等)
这是我想要改进的当前解决方案。
public interface IRule
{
bool Validate();
}
class Rule1 : IRule
{
public Rule1(string name) { ... }
bool Validate() { ... }
}
class Rule2 : IRule
{
public Rule1(int month, int year) { ... }
bool Validate() { ... }
}
interface IPaymentProcessor
{
bool MakePayment(CreditCard card);
}
class MyPaymentProcess : IPaymentProcessor
{
public bool MakePayment(CreditCard card)
{
// Here is pitfall. If we need to add/remove another rule or one of
// ctors changed, then we have to edit this place, which isn't flexible
var rules = new List<IBusinessRule>() { new Rule1(card.Name), new Rule2(card.Month, card.Year) };
foreach(var r in rules) if(!r.Validate()) { return false; }
return true;
}
}
【问题讨论】:
-
也许你需要的是与 bool Validate(CreditCard card) 规则的接口,而不仅仅是 Validate()。
-
是的,应该很方便,但是我把这个代码作为任务从其他人那里得到,不能修改。
-
无论如何将名称和其他数据传递给构造函数都行不通,您需要将整个 CreditCard 以一种或另一种形式传递给规则。
-
是 - 用于生产代码,否 - 用于测试任务 ;)
标签: c# .net architecture ninject abstraction