class Program
{
static void Main(string[] args)
{
Alarm alarm = new();
alarm.Subscribe(new FireStation());
alarm.Dispose();
alarm.Dispose();
alarm.Dispose();
alarm.Dispose();
alarm.Dispose();
}
}
// Object, that we are observing
// Object observable "sends" observed value, in our case its an int
public class Alarm : IObservable<int>, IDisposable
{
List<IObserver<int>> watchers = new();
// Methods Subscribe and Dispose are generated when you inherit from these IObsarvable and IDisposable interfaces
public IDisposable Subscribe(IObserver<int> observer)
{
watchers.Add(observer);
return this;
}
int i = 0;
public void Dispose()
{
if (i > 3)
{
watchers.ForEach(x => x.OnCompleted());
return;
}
watchers.ForEach(x => x.OnNext(i++));
}
}
// Object, that observes observed object
// Object observes seeked value - int
public class FireStation : IObserver<int>
{
// Methods are generated when you inherit from IObserver interface
public void Alert(Alarm value)
{
Console.WriteLine($"{nameof(FireStation)} RESPONDING!");
}
public void OnCompleted()
{
Console.WriteLine($"{nameof(FireStation)} COMPLETE!");
}
public void OnError(Exception error)
{
Console.WriteLine($"{nameof(FireStation)} ERROR!");
}
public void OnNext(int value)
{
Console.WriteLine($"{nameof(FireStation)} next: {value}");
}
}
Observer Design Pattern
Jack Herer
105
Reputation points
This is easy example on how to implement observer design pattern. Hope someone finds it helpful :)
2 answers
Sort by: Most helpful
-
Jack Herer 105 Reputation points
2023-04-22T19:36:22.4633333+00:00 -
Bruce (SqlWork.com) 61,731 Reputation points
2023-04-23T15:01:56.3766667+00:00 your Dispose implementation is suspect. Dispose() should only be called once. Typically implantation detects additional calls. also in The Observer pattern only an unsubscribe of observers makes sense. also the counter does not make sense.
typically with the Observer pattern, you would have an unsubscribe (also done automatically at Dispose). You also appear to missing the send message/event to subscriber.
typical Observer pattern in different languages (including c#):