using System;
using System.Collections;//.Generic;
//using System.Text;
// Rethrow an exception.
public interface Subject
{
void registerObserver(Observer o);
void removeObserver(Observer o);
void notifyObserver();
}
public interface Observer
{
void update();
}
public class Journalism : Subject
{
private ArrayList observers;
public Journalism()
{
observers = new ArrayList();
}
public void registerObserver(Observer o)
{
observers.Add(o);
}
public void removeObserver(Observer o)
{
//int i = observers.IndexOf(o);
//if (i >= 0)
observers.RemoveAt(observers.IndexOf(o));
}
public void notifyObserver()
{
for (int i = 0; i < observers.Count; i++)
((Observer)observers[i]).update();
}
}
public class Tom : Observer
{
public Tom(Subject jmaker)
{
jmaker.registerObserver(this);
}
public void update()
{
Console.WriteLine("Tom got the journal");
}
}
public class Joanne : Observer
{
public Joanne(Subject jmaker)
{
jmaker.registerObserver(this);
}
public void update()
{
Console.WriteLine("Joanne got the journal");
}
}
class ObserverPattern
{
public static void Main()
{
Journalism jmaker = new Journalism();
// Tom and Joanne order journals
Observer tom = new Tom(jmaker);
Observer joanne = new Joanne(jmaker);
// Inform all registrants
jmaker.notifyObserver();
Console.WriteLine("");
// Tom cancels to order journals
jmaker.removeObserver(joanne);
// Inform all registrants
jmaker.notifyObserver();
}
}
using System.Collections;//.Generic;
//using System.Text;
// Rethrow an exception.
public interface Subject
{
void registerObserver(Observer o);
void removeObserver(Observer o);
void notifyObserver();
}
public interface Observer
{
void update();
}
public class Journalism : Subject
{
private ArrayList observers;
public Journalism()
{
observers = new ArrayList();
}
public void registerObserver(Observer o)
{
observers.Add(o);
}
public void removeObserver(Observer o)
{
//int i = observers.IndexOf(o);
//if (i >= 0)
observers.RemoveAt(observers.IndexOf(o));
}
public void notifyObserver()
{
for (int i = 0; i < observers.Count; i++)
((Observer)observers[i]).update();
}
}
public class Tom : Observer
{
public Tom(Subject jmaker)
{
jmaker.registerObserver(this);
}
public void update()
{
Console.WriteLine("Tom got the journal");
}
}
public class Joanne : Observer
{
public Joanne(Subject jmaker)
{
jmaker.registerObserver(this);
}
public void update()
{
Console.WriteLine("Joanne got the journal");
}
}
class ObserverPattern
{
public static void Main()
{
Journalism jmaker = new Journalism();
// Tom and Joanne order journals
Observer tom = new Tom(jmaker);
Observer joanne = new Joanne(jmaker);
// Inform all registrants
jmaker.notifyObserver();
Console.WriteLine("");
// Tom cancels to order journals
jmaker.removeObserver(joanne);
// Inform all registrants
jmaker.notifyObserver();
}
}