Pregunta

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. enter image description here

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:

enter image description here

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?

¿Fue útil?

Solución

That would work, however you have some issues with your design and what you described.

  1. In transitioning to each state rules need to be fired and validate input object - your design does not cover this
  2. State changing is not managed anywhere so you are going to scatter that logic in your StateFacotry or elsewhere and handle it manually.

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:

  1. StateMachine can register a graph of state (S1->S2,S3 | S2->END | S3->S4 | S4->END)
  2. State transitioning happens automatically based on register graph and
  3. Each State knows what are the required rules to be met to allow the transition happens successfully. (Self-descriptive)
  4. StateMachine has not exposed the logic how the states are transitioning and all encapsulated in that implementation
  5. StateMAchine is independent of what the actual object is and manages all the transition logic plus validation execution (that you can simply integrate a full-fledged validation engine into your state machine)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top