Advertisement
Slash18

Observer

Jun 22nd, 2016
412
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.91 KB | None | 0 0
  1.  
  2. //    Full Tutorial on indiedevart.wordpress.com
  3.  
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9.  
  10. namespace ConsoleApplication5
  11. {
  12.     class Program
  13.     {
  14.         static void Main(string[] args)
  15.         {
  16.             Enemy subject = new Enemy();
  17.            
  18.             IObserver observer1 = new UserInteface();
  19.             subject.Subscribe(observer1);
  20.            
  21.             subject.Subscribe(new DifferentUnit());
  22.             subject.Health++;
  23.             Console.WriteLine("--------------------");
  24.             subject.Unsubscribe(observer1);
  25.             subject.Health--;
  26.             Console.ReadLine();
  27.         }
  28.     }
  29.     public class Enemy : IEnemy
  30.     {
  31.         private List<IObserver> observers = new List<IObserver>();
  32.         private int _health=10;
  33.         public int Health
  34.         {
  35.             get { return _health; }
  36.             set
  37.             {
  38.                 _health = value;
  39.                 Notify();
  40.             }
  41.         }
  42.  
  43.         public void Notify()
  44.         {
  45.             observers.ForEach(x => x.Update());
  46.         }
  47.  
  48.         public void Subscribe(IObserver observer)
  49.         {
  50.             observers.Add(observer);
  51.         }
  52.  
  53.         public void Unsubscribe(IObserver observer)
  54.         {
  55.             observers.Remove(observer);
  56.         }
  57.     }
  58.  
  59.     interface IEnemy
  60.     {
  61.         void Subscribe(IObserver observer);
  62.         void Unsubscribe(IObserver observer);
  63.         void Notify();
  64.     }
  65.     public class UserInteface : IObserver
  66.     {
  67.  
  68.         public void Update()
  69.         {
  70.             Console.WriteLine("Interface Updated");
  71.         }
  72.     }
  73.     public class DifferentUnit : IObserver
  74.     {
  75.  
  76.         public void Update()
  77.         {
  78.             Console.WriteLine("Relation Updated");
  79.         }
  80.     }
  81.  
  82.     public interface IObserver
  83.     {
  84.         void Update();
  85.     }
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement