Created
July 19, 2020 15:36
-
-
Save ShreyasJejurkar/48ed01bb3650ebbab89d4361472fe8d0 to your computer and use it in GitHub Desktop.
This file contains 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
using System; | |
using System.Collections.Generic; | |
namespace ObserverDesignPattern | |
{ | |
public class Program | |
{ | |
public static void Main() | |
{ | |
// our two users | |
User firstUser = new User("First"); | |
User secondUser = new User("Second"); | |
// our channel | |
YoutubeChannel learnDotnet = new YoutubeChannel(); | |
// Both user subscribe channed | |
learnDotnet.Subscribe(firstUser); | |
learnDotnet.Subscribe(secondUser); | |
// uploaded new video | |
learnDotnet.UploadNewVideo(); | |
Console.WriteLine("============================================="); | |
//second user is no more intrested so he unscribe. | |
learnDotnet.UnSubscribe(secondUser); | |
// uploads new video but secondUser wont be notified as he is no more subscriber | |
learnDotnet.UploadNewVideo(); | |
} | |
} | |
public interface ISubject {} | |
public interface IObserver | |
{ | |
void Notify(); | |
} | |
public class YoutubeChannel : ISubject | |
{ | |
private List<IObserver> subscribersList = new List<IObserver>(); | |
public void Subscribe(IObserver observer) => subscribersList.Add(observer); | |
public void UnSubscribe(IObserver observer) => subscribersList.Remove(observer); | |
public void UploadNewVideo() | |
{ | |
Console.WriteLine("New video has been uploaded"); | |
foreach(var o in subscribersList) | |
{ | |
o.Notify(); | |
} | |
} | |
} | |
public class User : IObserver | |
{ | |
private string _name { get; set; } | |
public User(string username) | |
{ | |
_name = username; | |
} | |
public void Notify() | |
{ | |
Console.WriteLine($"User {_name} has been notified for new video"); | |
} | |
} | |
} |
This file contains 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
New video has been uploaded | |
User First has been notified for new video | |
User Second has been notified for new video | |
============================================= | |
New video has been uploaded | |
User First has been notified for new video |
This file contains 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
{ | |
"version": 1, | |
"target": "Run", | |
"mode": "Debug" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment