我想使用Specification
模式在我的N-Layerd DDD
应用程序中应用业务规则。 我在模式中使用了我的Application Layer
也。 所以我定义我Domain
以下Interface
:使用业务规则的规范模式重构代码
public interface ISpecification<T>
{
Expression<Func<T, bool>> Predicate { get; }
bool IsSatisfiedBy(T entity);
}
,也有一些Specification
S上方的接口,实现诸如BigOrderSpecification : ISpecification<Order>
和SpecialOrderSpecification:ISpecification<Order>
。
我用下面的处理程序来处理我的订单:
public class OrderProcessCommandHandler : ICommandHandler<Order>
{
OrderCommand _command;
public OrderProcessCommandHandler(OrderCommand command)
{
_command = command;
}
public Handle()
{
var bigOrderSpec = new BigOrderSpecification();
var specialOrderSpec = new SpecialOrderSpecification();
var spec = bigOrderSpec.And(specialOrderSpec);
if (spec.IsSatisfiedBy(_commnand.Order))
// do some things
else
throw new BusinessException("Some business rules violated.")
}
}
我认为OrderProcessCommandHandler
的Handle()
方法,违反
- 的
Tell don't ask
原则,因为他从Order
问BR
满意的结果,然后决定做点什么。 Open/Close
原理,因为如果我想添加另一个规范,我必须更改我的CommandHandler
。我该如何重构我的代码以防止这种违规行为?
+1。而且,如果你注入你的依赖关系(即规范),你可以在处理程序之外编写规范,并且规范组合中的更改根本不会影响处理程序类。 –