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
110
Reputation points
This is easy example on how to implement observer design pattern. Hope someone finds it helpful :)
.NET
.NET
Microsoft Technologies based on the .NET software framework.
4,103 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,559 questions
2 answers
Sort by: Most helpful
-
Jack Herer 110 Reputation points
2023-04-22T19:36:22.4633333+00:00 -
Bruce (SqlWork.com) 77,631 Reputation points Volunteer Moderator
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#):