Observer design pattern is a behavioral pattern.In this pattern the particiapnts are the Subject and number of Observer objects.Observer object are interested in being notified of the state changes in the Subject.When the state of the Subject changes ,observers are notified of the state changes.There is one to many relationship between the Subject and the observers as one subject maintains a list of observer objects.
To receive updates about the state change of the Subject observer objects needs to register themselves with the subject.When the state of the Subject changes all the registered observer objects are notified of the state change.To stop getting notified of the state changes Subject provides the UnSubscribe method which the observers uses to stop getting notified of the state changes.
Example of Observer Pattern
In the following example we have two entities Library and the Readers.Library represents a library of books from where Readers can borrow and read books.From time to time new books are added to the collection of books in the Library.Reader can know which new book is added to the library.To get the information about the new book Reader needs to subscribe to the library.
When the new book is added all the subscribed readers are informed about the addition of the book.
Library class implements the interface ILibrary which provides methods to Subscribe and Unsubscribe readers.It also maintains a collection of books.
interface ILibrary { void Subscribe(Reader observer); void Unsubscribe(Reader observer); void Notify(Book book); } public class Library : ILibrary { private List<Reader> observers = new List<Reader>(); public List<Book> books; public Library() { books = new List<Book>(); } public void AddBook(Book book) { books.Add(book); Notify(book); } public void Subscribe(Reader observer) { observers.Add(observer); } public void Unsubscribe(Reader observer) { observers.Remove(observer); } public void Notify(Book book) { observers.ForEach(x => x.Update(book)); } } public class Book { public string Name{get;set;} }
Readers are represented by the Reader class.The update method of the Reader class is called whenever a new Book is added to the collection of books in the Library.
public class Reader:IReader { public string Name { get; set; } public Reader(string name) { this.Name = name; } public void Update(Book book) { Console.WriteLine("Added a new book titled {0}",book.Name); } } interface IReader { void Update(Book book); }
Now whenever we add a new book in the library ,subscribed readers are notified of the addition of the book
static void Main(string[] args) { Library library = new Library(); //Subscribe a new reader library.Subscribe(new Reader("Reader1" )); //Add a new book in the library library.AddBook(new Book { Name = "C# Book" }); }
User is notified of the addition of the book:
This example of the Observer pattern can be represented with the following UML diagram
Leave a Reply