Wednesday, February 27, 2013

Super Simple Observer Pattern Example

I keep destroying my own blog postings by accident. I wrote a really cool one about four animals being poisioned by a nuclear explosion which served as an example of the observer pattern. It is gone now. I offer the following instead. First take in these three classes:

  1. namespace FubarApp.Objects
    {
       public class Foo
       {
          public bool IsAltered { get; set; }
          
          public Foo()
          {
             IsAltered = false;
          }
          
          public void UpdateAlteredState(bool value)
          {
             IsAltered = value;
          }
       }
    }
     
  2. namespace FubarApp.Objects
    {
       public class Bar
       {
          public bool IsAltered { get; set; }
          
          public Bar()
          {
             IsAltered = false;
          }
          
          public void UpdateAlteredState(bool value)
          {
             IsAltered = value;
          }
       }
    }
     
  3. using System;
    namespace FubarApp.Objects
    {
       public class Fubar
       {
          public Action AlterationStateUpdater;
       }
    }
     

Alright, here they are in action! (pun intended)

using FubarApp.Objects;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace FubarApp.Tests
{
   [TestClass]
   public class UnitTest
   {
      [TestMethod]
      public void Test()
      {
         
//start as false
         Foo foo = new Foo();
         Bar bar = new Bar();
         Assert.AreEqual(foo.IsAltered, false);
         Assert.AreEqual(bar.IsAltered, false);
         
         
//still false
         Fubar fubar = new Fubar();
         fubar.AlterationStateUpdater = foo.UpdateAlteredState;
         fubar.AlterationStateUpdater += bar.UpdateAlteredState;
         Assert.AreEqual(foo.IsAltered, false);
         Assert.AreEqual(bar.IsAltered, false);
         
         
//no longer false
         fubar.AlterationStateUpdater(true);
         Assert.AreEqual(foo.IsAltered, true);
         Assert.AreEqual(bar.IsAltered, true);
      }
   }
}

No comments:

Post a Comment