Software Design Patterns Explainer
The Observer Design Pattern is a behavioral design pattern that allows one object (the subject) to notify other objects (the observers) about changes to its state. Observers subscribe to the subject, and whenever the subject's state changes, it sends notifications to all the subscribed observers.
This design pattern is perfect for your chat application, where you might have a chat room (the subject) and multiple users (the observers). Whenever a new message is posted in the chat room, all users should be notified and receive that message.
Here's an example in C#:
public interface IObserver { void Update(string message); } public interface ISubject { void Subscribe(IObserver observer); void Unsubscribe(IObserver observer); void Notify(string message); } public class ChatRoom : ISubject { private List<IObserver> observers = new List<IObserver>(); public void Subscribe(IObserver observer) { observers.Add(observer); } public void Unsubscribe(IObserver observer) { observers.Remove(observer); } public void Notify(string message) { foreach (var observer in observers) { observer.Update(message); } } public void NewMessage(string message) { Notify(message); } } public class User : IObserver { private string name; public User(string name) { this.name = name; } public void Update(string message) { Console.WriteLine($"{name} received: {message}"); } }
In this code, we define an observer interface (
IObserver
) with anUpdate
method and a subject interface (ISubject
) withSubscribe
,Unsubscribe
, andNotify
methods.
ChatRoom
implementsISubject
. It keeps a list of observers and notifies them whenNewMessage
is called.
User
implementsIObserver
and just prints the received message to the console when itsUpdate
method is called.To use this, you could do:
var chatRoom = new ChatRoom(); var alice = new User("Alice"); var bob = new User("Bob"); chatRoom.Subscribe(alice); chatRoom.Subscribe(bob); chatRoom.NewMessage("Hello, World!"); // Both Alice and Bob receive the message
This way, you can manage state changes in your chat application in a more controlled and efficient manner. It also aligns well with the SOLID principles, particularly the Single Responsibility Principle (each class has a clear, single responsibility) and the Open-Closed Principle (you can add new observers without modifying the subject).