In my recent project i have an Order
class that its properties will be complete step by step by different users, and each user refer the partial completed order to next user(s), so i assume each Order
has a Status
at each time, for example when an Order
creates, its Status
will be NewStatus
, when BOM(Bill of material) specified for it, its Status
will be BOMAttachedStatus
, when it planned for production its Status
will be PlannedStatus
, and so on.
Also i need apply some validation rules in each step to the Order
, e.g user must specify customer name when create an Order
(NewState
), or user must set PlanningDate when Order
is planning(PlannedStatus
), ...
So, i decided to use State Design Pattern to manage states, and also use Factory Design Pattern to check validations:
public static class StatusFactory
{
static public IStatus CreateOrderStatus(Order order)
{
//check statuses from last to first
if (order.PlanningDate != null)
return new PlannedStatus();
....
if(order.CustomerName != string.Empty)
return new OrderItemNewState();
}
}
and when i want to save my currentOrder
, i call StateFactory.CreateOrderStatus(currentOrder)
to set its Status
:
public void Save(Order order)
{
order.Status = StatusFactory.CreateOrderStatus(order);
UnitOfWork.SaveChanges();
}
Is this method correct for my case? is there any better solution?
That would work, however you have some issues with your design and what you described.
What I would to is creating a StateMachine class that you can simply call Transition method and provide a target State. The transition method queries from State to know what rules need to be validated and calls validation method. If successful then it changes the state of object.
Benefit of this design: