Last active
January 14, 2022 22:28
-
-
Save zekroTJA/03bcb3e2baf6546c1319cd5c9268798a to your computer and use it in GitHub Desktop.
C# .NET Publisher-Subscriber-Pattern example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // SOURCE: | |
| // https://www.codeproject.com/articles/866547/publisher-subscriber-pattern-with-event-delegate-a | |
| using System; | |
| namespace DotNetTest | |
| { | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| var pub = new Publisher(); | |
| var sub1 = new Subscriber(pub); | |
| var sub2 = new Subscriber(pub); | |
| sub1.Publisher.Handler += delegate (object sender, Message msg) | |
| { | |
| Console.WriteLine($"Sub1: {msg.Content}"); | |
| }; | |
| sub2.Publisher.Handler += delegate (object sender, Message msg) | |
| { | |
| Console.WriteLine($"Sub2: {msg.Content}"); | |
| }; | |
| pub.Publish("hey"); | |
| Console.ReadKey(); | |
| } | |
| } | |
| class Message | |
| { | |
| public string Content { get; set; } | |
| public Message(string _content) | |
| { | |
| Content = _content; | |
| } | |
| } | |
| interface IPublisher | |
| { | |
| event EventHandler<Message> Handler; | |
| void Publish(string cont); | |
| } | |
| class Publisher : IPublisher | |
| { | |
| public event EventHandler<Message> Handler; | |
| public void OnPublish(Message msg) | |
| { | |
| Handler?.Invoke(this, msg); | |
| } | |
| public void Publish(string cont) | |
| { | |
| Message msg = (Message)Activator.CreateInstance(typeof(Message), cont); | |
| OnPublish(msg); | |
| } | |
| } | |
| class Subscriber | |
| { | |
| public IPublisher Publisher { get; set; } | |
| public Subscriber(IPublisher publisher) | |
| { | |
| Publisher = publisher; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment