Skip to content

Instantly share code, notes, and snippets.

@fsmoraes
Last active February 1, 2019 18:24
Show Gist options
  • Save fsmoraes/980f512cb04c9e592e247b896c5806f3 to your computer and use it in GitHub Desktop.
Save fsmoraes/980f512cb04c9e592e247b896c5806f3 to your computer and use it in GitHub Desktop.
NotificationPattern
using System.Collections.Generic;
using static System.Console;
namespace NotificationPattern
{
class Program
{
static void Main()
{
var userWithoutEmailAndPassword = new User(null, null);
var userWithoutPassword = new User("user@gmail.com", null);
var userWithoutEmail = new User(null, "duvidei_descobrir_minha_senha_HAHAHAHAHA");
var user = new User("user@gmail.com", "duvidei_descobrir_minha_senha_HAHAHAHAHA");
if (!userWithoutEmailAndPassword.IsValid())
{
WriteLine($"userWithoutEmailAndPassword = {string.Join("; ", userWithoutEmailAndPassword.Notifications)}");
}
if (!userWithoutPassword.IsValid())
{
WriteLine($"userWithoutPassword = {string.Join("; ", userWithoutPassword.Notifications)}");
}
if (!userWithoutEmail.IsValid())
{
WriteLine($"userWithoutEmail = {string.Join("; ", userWithoutEmail.Notifications)}");
}
if (user.IsValid())
{
WriteLine($"User is valid!");
}
ReadKey();
}
}
public class Notification
{
public Notification(string code, string message)
{
Code = code;
Message = message;
}
public string Code { get; }
public string Message { get; }
public override string ToString() => Message;
}
public abstract class Notifiable
{
private List<Notification> _notifications;
public IReadOnlyCollection<Notification> Notifications => InternalNotifications;
private List<Notification> InternalNotifications
{
get
{
if (_notifications == null)
{
_notifications = new List<Notification>();
}
return _notifications;
}
}
public void AddNotification(Notification notification)
{
if (notification != null)
InternalNotifications.Add(notification);
}
public void ClearNotifications() => _notifications = null;
public bool IsValid() => InternalNotifications.Count == 0;
}
public class User : Notifiable
{
public User(string email, string password)
{
Email = email;
Password = password;
if (string.IsNullOrEmpty(Email))
{
AddNotification(new Notification("USU-01", "Email must be informed."));
}
if (string.IsNullOrEmpty(Password))
{
AddNotification(new Notification("USU-02", "Password must be informed."));
}
}
public string Email { get; private set; }
public string Password { get; private set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment