我有一个实体Order
,其属性为Status
。状态将为Enum,例如“新建”,“已处理”,“禁用”等。我有一组动作,如DeleteOrder,DuplicateOrder..etc。
将根据状态提供操作。将Order实例传递给方法时,需要获取操作列表。我该如何实现。我有以下模式。
public class Order (entity)
{
public int Id { get; set; }
public OrderStatus Status { get; set; }
}
public enum OrderStatus
{
New,
Processed,
Disable
}
public class OrderActionModel
{
public int Id { get; set; }
public OrderAction Action { get; set; }
public string Comments { get; set; }
}
public enum OrderAction
{
DeleteOrder,
DuplicateOrder
}
public interface IAction
{
void Process();
}
public interface IActionFactory
{
IAction GetAction(OrderActionModel model);
List<string> GetActions(Order order);
}
public class ActionFactory : IActionFactory
{
private readonly IMailService _mailService;
public ActionFactory(IMailService mailService)
{
_mailService = mailService;
}
public IAction GetAction(OrderActionModel model)
{
switch (model.Action)
{
case DeleteOrder:
return new DeleteOrderAction(model, _mailService);
case DuplicateOrder:
return new DuplicateOrderAction(model, _mailService);
default:
return null;
}
}
public List<string> GetActions(Order order)
{
//How to call isValidAction from here for each list of actions
}
}
public class DeleteOrderAction : IAction
{
private OrderActionModel _model;
private readonly IMailService _mailService;
public DeleteOrderAction(OrderActionModel model, IMailService mailService)
{
_model = model;
_repository = repository;
}
public void Process()
{
AddAudit(_model.comments);
SendEMail();
}
public bool IsValidAction(Order order)
{
return order.Status == OrderStatus.New;
}
}
public IHttpActionResult Action(OrderActionModel model)
{
IAction action = _actionFactory.GetAction(model);
action.Process();
return Ok();
}
public IHttpActionResult GetActions(1)
{
//get order by id
var order = repo.getOrder(1)
//Some method to get Actions
var actions = SampleMethod(order)
return Ok(actions);
}
答案 0 :(得分:0)
因此,如果您要坚持使用此模型,那么实现所需目标的最简单方法就是
$this->user()
您在应用初始化期间将您的操作及其相关的验证功能放在一起,所以
Dictionary<string, Func<Order, bool>> actionNameToViableCheck;
这要求actionNameToViableCheck.Add("Delete Order", o => DeleteOrderAction.IsValidOrder(o));
方法为IsValidOrder
。
然后您的static
可能看起来像这样:
GetActions
请注意,如果有许多不同的操作,这并不是最有效的解决方案,因为您每次都处理所有这些操作。但是,由于您是通过动作的public List<string> GetActions(Order order) =>
actionNameToViableCheck.Where(kv => kv.Value(order)).Select(kv => kv.Key);
方法输出定义动作有效性的,所以我看不出一种更好的简单方法。