public abstract class NotificationType
{
public string Name { get; }
protected NotificationType(string name)
{
Name = name;
}
public abstract void Send(string message);
public abstract bool Validate(string input);
public static readonly NotificationType Email = new EmailType();
public static readonly NotificationType Sms = new SmsType();
public static readonly NotificationType PushLine = new PushLineType();
}
static readonly 用來模擬 enum value
2. 寫三個 Smart Enum Value(每個都有自己的行為)
public sealed class EmailType : NotificationType
{
public EmailType() : base("Email") { }
public override bool Validate(string email)
{
//Validate Email Logic
return email.Contains("@");
}
public override void Send(string message)
{
//Send Logic
Console.WriteLine("Send email:" + message);
}
}
public sealed class SmsType : NotificationType
{
public SmsType() : base("SMS") { }
public override bool Validate(string number)
{
//Validate Text Logic
return number.StartsWith("09") && number.Length == 10;
}
public override void Send(string message)
{
Console.WriteLine("Send SMS:" + message);
//Send Logic
}
}
public sealed class PushLineType : NotificationType
{
public PushLineType() : base("PushLine") { }
public override bool Validate(string token)
{
return token.Length > 10;
}
public override void Send(string message)
=> Console.WriteLine($"Send Push: {message}");
}
每個 Smart Enum value 有自己的 驗證邏輯、發送邏輯
3. 接下來就不用 switch 了
var typeSMS = NotificationType.Sms;
if (typeSMS.Validate("0912345678"))
{
typeSMS.Send("Hello! Moto!");
}
var typeLine = NotificationType.PushLine;
if (typeLine.Validate("token-123456789"))
{
typeLine.Send("Hello! LINE!");
}
var typeEmail = NotificationType.Email;
if (typeLine.Validate("foo@sample.com"))
{
typeLine.Send("Hello! EMAIL!");
}
//Send SMS:Hello! Moto!
//Send Push: Hello! LINE!
//Send Push: Hello! EMAIL!