Wednesday, September 22, 2010

Simple abstraction and decoupling example

Just code.


We have a logger and a log viewer, could be better but I wanted it to be simple.


This is the window that is also the log viewer
/// <summary>
  /// Interaction logic for MainWindow.xaml
  /// </summary>
  public partial class MainWindow : Window, ILogViewer
  {
    public MainWindow()
    {
      InitializeComponent();
      Logger.RegisterViewer(this);
    }

    public void Log(string message)
    {
      // do the write logic
    }
  }

This is the interface of viewers
public interface ILogViewer
{
  void Log(string message);
}
This is logger
public static class Logger
{
  static List<ILogViewer> viewers = new List<ILogViewer>();

  public static void RegisterViewer(ILogViewer viewer)
  {
    viewers.Add(viewer);
  }

  public static void Log(string message)
  {
    foreach (ILogViewer viewer in viewers)
    {
      viewer.Log(message);
    }
  }
}