Add observer pattern

This commit is contained in:
Alex Hyett 2023-09-04 10:56:02 +01:00
parent ff3bed5c69
commit 27045cc4b9
6 changed files with 98 additions and 0 deletions

8
Observer/IPublisher.cs Normal file
View file

@ -0,0 +1,8 @@
public interface IPublisher
{
void Subscribe(ISubscriber subscriber);
void Unsubscribe(ISubscriber subscriber);
void Notify();
}

5
Observer/ISubscriber.cs Normal file
View file

@ -0,0 +1,5 @@
public interface ISubscriber
{
string Name { get; }
void Update(IPublisher subject);
}

10
Observer/Observer.csproj Normal file
View file

@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

16
Observer/Program.cs Normal file
View file

@ -0,0 +1,16 @@

var publisher = new Publisher();
var subscriberA = new Subscriber("Alex");
publisher.Subscribe(subscriberA);
var subscriberB = new Subscriber("Bob");
publisher.Subscribe(subscriberB);
publisher.PublishNewsletter();
publisher.PublishNewsletter();
publisher.PublishNewsletter();
publisher.Unsubscribe(subscriberB);
publisher.PublishNewsletter();

35
Observer/Publisher.cs Normal file
View file

@ -0,0 +1,35 @@
public class Publisher : IPublisher
{
public int IssueNumber { get; set; } = 0;
private List<ISubscriber> _subscribers = new List<ISubscriber>();
public void Subscribe(ISubscriber subscriber)
{
Console.WriteLine($"Publisher: {subscriber.Name} just subscribed");
_subscribers.Add(subscriber);
}
public void Unsubscribe(ISubscriber subscriber)
{
_subscribers.Remove(subscriber);
Console.WriteLine($"Publisher: {subscriber.Name} just unsubscribed");
}
public void Notify()
{
Console.WriteLine("Publisher: Notify subscribers...");
foreach (var subscriber in _subscribers)
{
subscriber.Update(this);
}
}
public void PublishNewsletter()
{
this.IssueNumber++;
Console.WriteLine($"Published #{this.IssueNumber} of Newsletter");
this.Notify();
}
}

24
Observer/Subscriber.cs Normal file
View file

@ -0,0 +1,24 @@
public class Subscriber : ISubscriber
{
private int _latestIssue = 0;
public Subscriber(string name)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
}
public string Name
{
get; private set;
}
public void Update(IPublisher publisher)
{
var concretePublisher = (publisher as Publisher);
if (concretePublisher.IssueNumber > _latestIssue)
{
_latestIssue = concretePublisher.IssueNumber;
Console.WriteLine($"{Name}: Received Issue {_latestIssue}");
}
}
}