Skip to content

Instantly share code, notes, and snippets.

@ArseniySavin
Last active July 25, 2022 09:29
Show Gist options
  • Save ArseniySavin/d54632a9c1cca5471bc4857265b1c2bb to your computer and use it in GitHub Desktop.
Save ArseniySavin/d54632a9c1cca5471bc4857265b1c2bb to your computer and use it in GitHub Desktop.
Rule prototype pattern for validation
var phone = "+77771112233"
var record = GetRecordById(Id);
new RulePrototypeConcrete()
.With(new ChangePhoneRule(phone))
.With(new DeletePhoneRule(phone))
.With(new ExistsPhoneRule(phone))
.Execute(record);
public abstract class RulePrototype : IDisposable
{
protected List<Rule> rules = new List<Rule>();
public abstract RulePrototype With(Rule rule);
public abstract AgentResult Execute(CardSMSApplication cardApp);
public void Dispose()
{
rules.Clear();
}
}
public abstract class Rule
{
protected bool isResult = false;
protected AgentResult result = new AgentResult();
public abstract bool IsExecute { get; protected set; }
internal abstract AgentResult GetResult(TestApplication app);
}
public class RulePrototypeConcrete : RulePrototype
{
public override RulePrototype With(Rule rule)
{
rules.Add(rule);
return this;
}
public override AgentResult Execute(TestApplication app)
{
AgentResult result = new AgentResult();
foreach(Rule r in rules)
{
result = r.GetResult(app);
if(r.IsExecute)
break;
}
return result;
}
}
public class ChangePhoneRule : Rule
{
string _phone;
public ChangePhoneRule(string phone)
{
_phone = phone;
}
public override bool IsExecute
{
get
{
return isResult;
}
protected set
{
isResult = value;
}
}
internal override AgentResult GetResult(TestApplication app)
{
if(app.ReasonType == AppType.CHNG && app.NewPhone == _phone)
{
...... DO Somting ......
IsExecute = true;
result = FailValidation.GetError("ERROR");
}
return result;
}
}
public class DeletePhoneRule : Rule
{
string _phone;
public ChangePhoneRule(string phone)
{
_phone = phone;
}
public override bool IsExecute
{
get
{
return isResult;
}
protected set
{
isResult = value;
}
}
internal override AgentResult GetResult(TestApplication app)
{
if(app.ReasonType == AppType.CHNG && app.NewPhone == _phone)
{
...... DO Somting ......
IsExecute = true;
result = FailValidation.GetError("ERROR");
}
return result;
}
}
public class ExistsPhoneRule : Rule
{
string _phone;
public ChangePhoneRule(string phone)
{
_phone = phone;
}
public override bool IsExecute
{
get
{
return isResult;
}
protected set
{
isResult = value;
}
}
internal override AgentResult GetResult(TestApplication app)
{
if(app.ReasonType == AppType.CHNG && app.NewPhone == _phone)
{
...... DO Somting ......
IsExecute = true;
result = FailValidation.GetError("ERROR");
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment