我正在尝试为多页注册表单实现状态模式。每页上的数据将被累积并存储在会话对象中。
是否应在页面级别或每个州级别内部进行验证(包括对数据库的服务层调用)?换句话说,IState的具体实现应该与验证有关还是应该给予一个完全填充和有效的对象?请参阅下面的“EmptyFormState”类:
namespace Example
{
public class Registrar
{
private readonly IState formEmptyState;
private readonly IState baseInformationComplete;
public RegistrarSessionData RegistrarSessionData { get; set;}
public Registrar()
{
RegistrarSessionData = new RegistrarSessionData();
formEmptyState = new EmptyFormState(this);
baseInformationComplete = new BasicInfoCompleteState(this);
State = formEmptyState;
}
public IState State { get; set; }
public void SubmitData(RegistrarSessionData data)
{
State.SubmitData(data);
}
public void ProceedToNextStep()
{
State.ProceedToNextStep();
}
}
//actual data stored in the session
//to be populated by page
public class RegistrarSessionData
{
public string FirstName { get; set; }
public string LastName { get; set; }
//will include values of all 4 forms
}
//State Interface
public interface IState
{
void SubmitData(RegistrarSessionData data);
void ProceedToNextStep();
}
//Concrete implementation of IState
//Beginning state - no data
public class EmptyFormState : IState
{
private readonly Registrar registrar;
public EmptyFormState(Registrar registrar)
{
this.registrar = registrar;
}
public void SubmitData(RegistrarSessionData data)
{
//Should Validation occur here?
//Should each state object contain a validation class? (IValidator ?)
//Should this throw an exception?
}
public void ProceedToNextStep()
{
registrar.State = new BasicInfoCompleteState(registrar);
}
}
//Next step, will have 4 in total
public class BasicInfoCompleteState : IState
{
private readonly Registrar registrar;
public BasicInfoCompleteState(Registrar registrar)
{
this.registrar = registrar;
}
public void SubmitData(RegistrarSessionData data)
{
//etc
}
public void ProceedToNextStep()
{
//etc
}
}
}
答案 0 :(得分:0)
我更喜欢在状态(集合)级别和最终提交时进行验证。总的来说,我更愿意尽快验证,作为良好用户体验的一部分。从数据验证/保护级别来看,我更倾向于在最终的保存/提交级别进行验证,以防万一被窃听,保护免受通用欺骗,或者(更可能)将来保存/提交点的不同路由。