I didn't like the example you linked, below I listed the reasons:
- I agree that the persisting architecture will be a mess - way to messy in my opinion.
- Creating new instance per state seems to me like efficiency suicidal pattern.
- Testing will be hell... finding errors will be hell.. debugging will be hell.
- In over 30 years of experience I never seen this pattern being used even once in a data centric application - I did see it and used it in cases where I do not need to persist the information, in example when building a network layer - per port could be treated with that kind of state pattern.
I would go for this pattern instead:
pattern infrastructure
public interface IStateObject<T>
{
T State { get; set; }
void Process();
}
Example implementation for some pseudo Order object
public enum OrderState
{
Taken,
Approved,
Payed,
Emailed,
BeforeShipment
//etc.. etc..
}
public class Order : IStateObject<OrderStates>
{
//some linear fields of order..
//: name, description, etc.. etc..
public OrderStates State { get; set; }
public void Process()
{
switch (State)
{
case OrderState.Taken:
// code to handle this state
break;
case OrderState.Approved:
// etc..
break;
}
//persist myself to db.
}
}
It is very simple as you can save object per type per context of the object in one row.
Also an object is created once as intuitively it should have if we had no computer nears us..
But mostly because it is very straight forward and very flexible.
You might notice you actually may not need the IStateObject<T>
at all - but I would argue you will need it later on when you want to process on vertical decisions.
keep in mind that T
doesn't have to be an enum. it could serve as common ground to evolve according to your app needs.
To further point out the mess I mentioned in the beginning of this answer,
Let's say we want to have history to previous states of the order:
Using the pattern offered in this answer - you add a PreviousOrderState property and now you have history per row.. And there are other ways I'm sure you can think of..
But using the "State Pattern" - you will be in serious problem... it will actually going to be complicated by a full "scale level" to do that.. you will have to be able to link from each type of table to each type of other table - or try to force Object Oriented on your database...
See my point? the States pattern is simply not designed for data centric apps.
Good Luck.