The observer design pattern can be used when you want objects to know when something happens to an object being observed.
This is done with a Subject and an Observer.
For example, let's say we have a Dragon that will be the subject and then have people as observers. When the dragon switches to a flying mode the observers will look up instead of forward.
To accomplish that we need an ISubject that will have the method to add, remove and notify observers.
- public interface IDragonSubject
- {
- void Subscribe(IDragonObserver observer);
- void Unsubscribe(IDragonObserver observer);
- void Notify();
- }
- public class Dragon : IDragonSubject
- {
- private IList<IDragonObserver> observers;
- private bool flying;
- public bool Flying
- {
- get { return flying; }
- set
- {
- if (flying != value)
- {
- flying = value;
- Notify();
- }
- }
- }
- public Dragon()
- {
- observers = new List<IDragonObserver>();
- }
- // People around will begin to watch this dragon
- public void Subscribe(IDragonObserver observer)
- {
- observers.Add(observer);
- }
- // if they get out of range we could unsubscribe
- public void Unsubscribe(IDragonObserver observer)
- {
- observers.Remove(observer);
- }
- // when something happens we will notify
- // all observers for this instance
- public void Notify()
- {
- foreach (var observer in observers)
- {
- observer.Update(this);
- }
- }
- }
- public class Person : IDragonObserver
- {
- public enum LookingDirectionTypes
- {
- Foward,
- Up,
- Down,
- Left,
- Right,
- }
- public LookingDirectionTypes LookingDirection { get; set; }
- public void Update(Dragon dragon)
- {
- if (dragon.Flying)
- LookingDirection = Person.LookingDirectionTypes.Up;
- else
- LookingDirection = LookingDirectionTypes.Foward;
- }
- }
- [TestClass]
- public class ObserverTest
- {
- [TestMethod]
- public void DragonFlyPeopleLookUp()
- {
- Dragon dragon = new Dragon();
- // default looking direction = Foward
- Person p1 = new Person();
- Person p2 = new Person();
- Person p3 = new Person();
- // p1 and p2 are now watching the dragon
- dragon.Subscribe(p1);
- dragon.Subscribe(p2);
- // the dragon started to fly
- dragon.Flying = true;
- Assert.AreEqual(Person.LookingDirectionTypes.Up, p1.LookingDirection);
- Assert.AreEqual(Person.LookingDirectionTypes.Up, p2.LookingDirection);
- Assert.AreEqual(Person.LookingDirectionTypes.Foward, p3.LookingDirection);
- }
- }

NitinPosted Jun 15, 2015, 10:30 AM
nice