Observer Design Pattern With Delegates And Events

In the previous post, I had demonstrated the Observer Design Pattern. The approach I showed is similar to the classic approach described in Gang Of Four (GoF) book. At the time of writing GoF book C++ was one of the most commonly used language. Over the period of time, different variants or derivatives of C++ languages emerged like Java and C#. These languages have built in support for many of the classic design patterns described in GoF. We tend to use these features baked into the language without even realizing that its an implementation of the design pattern. In todays post, which is a continuation of Design Patterns series, I am going to demonstrate the C# adaptation of Observer Design Pattern using Delegates and Events.

Problem Statement

There is no change in the problem statement which we had used in the last post. The requirement is exactly the same as it was before. I am going to refactor the solution from the previous post into the one which uses the C# language features like Delegates and Events. So lets get started.

Refactored Solution using Delegates & Events

In the previous post, we had used an IStockObserver interface to define the method signature that the Observers were going to use. Similar feature can be implemented  without using an interface. We can define a Delegate which defines the method signature that the observers should be using. Any method which has the same signature can be used as an observer. Here is the refactored version of the PortfolioManager class.

    internal class PortfolioManager

    {

        private readonly IList<Stock> stocks;

 

        public PortfolioManager()

        {

            stocks = new List<Stock>();

 

            // stockObservers = new List<IStockObserver>();

        }

 

        public delegate void StocksChangeHandler(ReadOnlyCollection<Stock> stocks);

 

        public event StocksChangeHandler StocksChanged;

 

        public ReadOnlyCollection<Stock> Stocks

        {

            get

            {

                return new ReadOnlyCollection<Stock>(stocks);

            }

        }

 

        // public void RegisterStockObserver(IStockObserver stockObserver)

        // {

        //    stockObservers.Add(stockObserver);

        // }

 

        public void AddStock(Stock stock)

        {

            stocks.Add(stock);

 

            // Notify();

            OnStocksChanged(Stocks);

        }

 

        public void RemoveStock(Stock stock)

        {

            stocks.Remove(stock);

 

            // Notify();

            OnStocksChanged(Stocks);

        }

 

        protected void OnStocksChanged(ReadOnlyCollection<Stock> currentStocks)

        {

            if (StocksChanged != null)

            {

                StocksChanged(currentStocks);

            }

        }

 

        //private void Notify()

        //{

        //    foreach (IStockObserver stockObserver in stockObservers)

        //    {

        //        stockObserver.Update(Stocks);

        //    }

        //}

    }

Note the lines just after the constructor. We declare a delegate StocksChangedHandler and an event named StocksChanged. As a result of this refactoring, we no longer need to maintain the list of IStockObserver in our PortfolioManager. All the plumbing is done by the framework through delegate. When the state changes, we can notify the observers on subscribers by invoking the delegate method. For easier comparison I have commented the code from previous blog.

We have replaced the Notify method from the previous implementation with a method named OnStocksChanged. This method checks if there are any subscribers for the StocksChanged event and invokes the delegate methods on those subscribers. With the refactoring the number of lines seem to remain the same but responsibility as to how we notify the changes in state gets affected slightly. Lets look at the subscription side of things.

    public class Shell

    {

        public Shell()

        {

            PortfolioManager portfolioManager = new PortfolioManager();

 

            StockGrid grid = new StockGrid();

 

            PieChart pieChart = new PieChart();

 

            // portfolioManager.RegisterStockObserver(grid);

            portfolioManager.StocksChanged += grid.Update;

 

            //portfolioManager.RegisterStockObserver(pieChart);

            portfolioManager.StocksChanged += pieChart.Update;

 

            portfolioManager.AddStock(new Stock());

 

            portfolioManager.StocksChanged -= pieChart.Update;

 

            portfolioManager.RemoveStock(portfolioManager.Stocks[0]);

        }

    }

There is not much change in the subscription part. Instead of registering the observer using a dedicated method, we use the C# language syntactical sugar to subscribe to the StocksChanged event. Earlier we used to pass the complete object like pieChart or grid. Now we just register the name of the method which matches the delegate method signature.

The last two lines are additional ones which I have added to show how we can unsubscribe for pieChart at runtime. If you imagine a GUI related app, this might be something like simulating a close of a widget which displays the pie chart component in the GUI. Finally we look at the observer classes.

    public class StockGrid

    {

        public void UpdateGrid(ReadOnlyCollection<Stock> stocks)

        {

            Console.WriteLine("Update grid called...");

        }

 

        public void Update(ReadOnlyCollection<Stock> stocks)

        {

            UpdateGrid(stocks);

        }

    }

As we see in this version there is no need for observer to implement the IStockObserver interface. We just need a method matching the signature of the delegate. In fact we can get rid of the delegation in the above code and directly register UpdateGrid as the subscriber for the event as it matches the delegate signature. I’ll leave it as an exercise for the reader to try it out.

Conclusion

As we saw from the refactored code, C# language has built in support for Observer Pattern. Not just C# other DotNet framework based languages like VB.Net etc also support delegates and events. Having build in support within the language saves developers from writing boilerplate code. I personally feel that this is a better approach compared to abstracting the Observer interface as shown in the earlier post.

As always, the complete working solution is available for download demo.zip.

Until next time happy Programming.

Further Reading

Here are some books I recommend related to the topics discussed in this blog.

spacer

Observer Design Pattern

This is the continuation of the Design Patterns series. In this post I am going to demonstrate the Observer Design Pattern.Observer is a behavioural design pattern in which an object notifies its dependents of the state changes.

Problem Statement

Assume that we are building a highly sophisticated financial Portfolio management system. We need to provide users the facility to build a portfolio to manage their stocks. The users should be able to add new stocks to their existing stocks. They should also be able to remove stocks from the portfolio. We need to show different representations of the data. The users should be shown the data in grid format as well as graphical format in the form of charts.  

Solution

Similar to the previous demos related to design patterns, I am not going to build any user interface for this post as well. Assume that the system has a full blown user interface which has a parent window containing all the jazzy UI elements like grid, graph, menu bar, toolbar, buttons etc. I’ll concentrate only on the classes in the context. If you wish you can build a UI and integrate the classes defined here.

Assume that the user can add stock details. They also have the ability to remove a stock. Based on the user actions, there will be a Grid which will get updated. Within the windows, there is also graphical representation of the data showing all the stocks as a pie chart grouped by the sector. This provides the user a summarized view of the portfolio and their exposure by the sector in which they have invested. So lets look at some of the classes we have in the solution. We’ll start with the Stock class which acts as the Model for our application.

    public class Stock

    {

        public string Name { get; set; }

 

        public int Price { get; set; }

 

        public Sector Sector { get; set; }

    }

Currently the Stock class has only 3 properties. Name, Price and Sector. Sector is an enum which can be of following types:

  • Banking
  • Automobile
  • IT
  • Minimg

Next we look at the PortfolioManager class

    public class PortfolioManager

    {

        private readonly IList<Stock> stocks;

 

        private readonly StockGrid grid;

 

        private readonly PieChart pieChart;

 

        public PortfolioManager()

        {

            stocks = new List<Stock>();

 

            grid = new StockGrid();

 

            pieChart = new PieChart();

        }

 

        public ReadOnlyCollection<Stock> Stocks

        {

            get

            {

                return new ReadOnlyCollection<Stock>(stocks);

            }

        }

 

        public void AddStock(Stock stock)

        {

            stocks.Add(stock);

 

            grid.UpdateGrid(Stocks);

 

            pieChart.DrawChart(Stocks);

        }

 

        public void RemoveStock(Stock stock)

        {

            stocks.Remove(stock);

 

            grid.UpdateGrid(stocks);

 

            pieChart.DrawChart(Stocks);

        }

    }

This is somewhat similar to a view model type of a class. This class provides the core functionality of adding and removing the stocks. There are two hypothetical classes named StockGrid and PieChart which we can think of as the ones which render the grid and the pie chart from the stocks data. Note that we call the UpdateGrid and DrawChart methods every time we add or remove a stocks from the portfolio.

Twist in the Tale

The users are very happy with the functionality and now wish to enhance it. They want to have other views of the portfolio. Along with the pie chart which displays the users exposure by Sector, they wish to visualize the portfolio as a Bar chart. The bars will be plotted against the Price of the Stock. Apart from the bar graph, the users also want to see the summary of stocks which displays the name and price of the highest and lowest stock.

We can refactor the above solution to make calls to two other class methods. We can define one class which displays the summary information. And another class which renders the bar chart. These two calls will need to be made from AddStock and RemoveStock methods. Looking back at this approach, it doesn’t look very good. If we look carefully, the underlying data is the same for all the different views. It is just that the different views needs to be updated when the Stocks collection is modified either by adding new stock or removing an existing stock.

The current approach makes the class holding the stocks collection dependent on the different views. The data and the representation of the data in the form of a grid, graphs and summary view are tightly coupled together. Imagine a situation where user has a dynamic screen and can choose from different views of the same data. In the same example, imagine that the user has finer control over the UI elements. He or she can choose what views are displayed in the window. Some users might choose to see only Pie chart and the Grid. Others might choose to add Grid, Pie chart, bar chart and summary view to their window. The combination can be anything as per the users choice.

In this scenario we will have to build some means of identifying if the Grid is chosen by the user or the Pie chart is chosen by the user. If the user has added a type of view like Grid to their UI then we need to call the respective method to update the current state of the stocks. In its current state the solution doesn’t look to scale well. What if we need another view of the stocks like a 3D chart. With every view that needs to be displayed in the UI we will have to have a reference in the portfolio manager class and invoke its respective method. If we could separate the two concerns it would be great.

Refactored Solution

Lets see how we can try and minimize the impact of the changes. How can we make sure that different views can be updated when the Stocks collection from PortfolioManager is modified? If we look at the methods of the PieChart and Grid class, they both depend on the current stocks collection. So we know that this is the data which all the different representations of the data will depend upon. So we can unify this and create an interface.

    public interface IStockObserver

    {

        void Update(ReadOnlyCollection<Stock> stocks);

    }

This interface has just one method Update which takes the Stocks collection as an input parameter. This simple interface makes our job easier within the PortfolioManager class. Instead of creating instances of each types like Grid or PieChart that depend on the stocks, we can depend on the abstraction. Lets see how this impacts our PortfolioManager.

We want to notify all the interested parties when the stock is added or removed. So lets define a method called Notify in our PortfolioManager class. This method is responsible for notifying all the interested parties when the state of the stocks collection changes.

        public void AddStock(Stock stock)

        {

            stocks.Add(stock);

 

            Notify();

        }

 

        public void RemoveStock(Stock stock)

        {

            stocks.Remove(stock);

 

            Notify();

        }

Here are our AddStock and RemoveStock methods. But how do we actually notify the interested receivers. For that we maintain a list of interested parties who would like to be notified about the state changes. The Notify method simply iterates over the collection of interested receivers and calls the Update method on them.

        private void Notify()

        {

            foreach (IStockObserver stockObserver in stockObservers)

            {

                stockObserver.Update(Stocks);

            }

        }

That also looks straightforward. So the next question is how do we populate the stockObservers collection. We expose a method RegisterStockObserver which allows the interested observers to register themselves with the PortfolioManager class.

        public void RegisterStockObserver(IStockObserver stockObserver)

        {

            stockObservers.Add(stockObserver);

        }

That completes our changes to the PortfolioManager class. One thing that is still not clear is how does the individual receivers like the Grid and PieChart respond to this change notification. As many of you would have guessed, its by implementing the IStockObserver interface. Here is the implementation of StockGrid class.

    public class StockGrid : IStockObserver

    {

        public void UpdateGrid(ReadOnlyCollection<Stock> stocks)

        {

        }

 

        public void Update(ReadOnlyCollection<Stock> stocks)

        {

            UpdateGrid(stocks);

        }

    }

Similar is the case with PieChart class.

    public class PieChart : IStockObserver

    {

        public void DrawChart(ReadOnlyCollection<Stock> stocks)

        {

        }

 

        public void Update(ReadOnlyCollection<Stock> stocks)

        {

            DrawChart(stocks);

        }

    }

Both these classes implement the IStockObserver interface. The update method delegates the call to the UpdateGrid and DrawChart methods in respective classes. If you wish you can implement the code directly within the Update method itself. I’ll leave the implementation of the BarChart and Summary views to you as an exercise.

Now we have the class which Notifies and other classes which can do some processing with the changed stocks. But we still haven’t linked the two pieces together. In our previous code, all the class instances were available within the PortfolioManager itself. As a result we could call the respective methods on the instances of StockGrid and Piechart to update them.

After the refactoring we need some additional work to link the PortfolioManager and the dependent classes together. Assume that we have some sort of boots trapper or a shell kind of class which instantiates these classes and links them together.

    public class Shell

    {

        public Shell()

        {

            PortfolioManager portfolioManager = new PortfolioManager();

 

            StockGrid grid = new StockGrid();

 

            PieChart pieChart = new PieChart();

 

            portfolioManager.RegisterStockObserver(grid);

 

            portfolioManager.RegisterStockObserver(pieChart);

 

            portfolioManager.AddStock(new Stock());

        }

    }

Here we create a Shell class which links all the pieces together. We create instances of PortfolioManager, StockGrid and PieChart classes. Then we register the gird and pie chart as observers with the PortfolioManager. And finally add a new stock. You can verify by running this code that both the grid as well as pie chart gets notified.

Conclusion

This was the demonstration of the classic Gang of Four (GoF) implementation of the Observer Design Pattern. We can use the terminology described in GoF book to relate to the classes we have in our refactored solution. The PortfolioManager is know as the Subject. It is the class which contains the state information. The StockGrid and the PieChart are called the Observers. There are the classes interested in the changes to the state of the subject. the Observer pattern is also know as Publisher Subscriber pattern.

We can use Observer to remove the tight coupling between the subject and its observers. In our case we can add any number of observer going forward. There are built in features within DotNet framework which make it even more easier to implement the Observer patter. I’ll talk about those in near future.

As always the complete solution is available for download ObserverDesignPatternDemo.zip.

Until next time Happy Programming.

Further Reading

Here are some books I recommend related to the topics discussed in this post.

spacer

Template Method Design Pattern

Continuing with the Design Patterns series, this post is about the Template Method design pattern. Template Method is a Behavioural design pattern which defers the exact steps of an algorithm to a subclass.

Problem Statement

Lets say we are building a data driven application. Like any other data driven business application, the end users of this system also needs to save data in different formats. The application should allow users to take a snapshot of the data and export it into their preferred format. We need to enable users to export data in PDF files or excel files. The contents of the file should contain a header, the report and the footer.

Solution without Template Method Design Pattern

Lets get started and build the required features. Assuming that we have fetched the data from respective data source, we can build one class for generating the PDF report and another one for generating the excel report. Lets get started with the PDF report writer.

    public class PDFReportWriter

    {

        public void WriteHeader()

        {

            // writes header details into PDF document

        }

 

        public void WriteReportContents()

        {

            // writes report into PDF document

        }

 

        public void WriteFooter()

        {

            // writes footer details into PDF document

        }

    }

The PDFReportWriter class consists of 3 methods one for each operation like Header, Contents and Footer to be written into the PDF file. I am not going into the details of the implementation of these methods. In reality we can use some library like iTextSharp which provides an API for generating PDF documents. The details of how we can output the contents to a PDF file outside the scope of this article.

Similar to the PDFReportWriter we can define an ExcelReportWriter class which can generate a report and save it in Excel format. To save some space, I am not going to copy the contents of the ExcelReportWriter here. You can find the source code it in the attached solution file.

Lets see how the client code which depends on these classes can make use of them.

    public class Client

    {

        public void GenerateReport(ReportType reportType)

        {

            if (reportType == ReportType.PDF)

            {

                PDFReportWriter pdfReportWriter = new PDFReportWriter();

 

                pdfReportWriter.WriteHeader();

                pdfReportWriter.WriteReportContents();

                pdfReportWriter.WriteFooter();

            }

 

            if (reportType == ReportType.EXCEL)

            {

                ExcelReportWriter excelReportWriter = new ExcelReportWriter();

 

                excelReportWriter.WriteHeader();

                excelReportWriter.WriteReportContents();

                excelReportWriter.WriteFooter();

            }

        }

    }

We have a class named Client which has a method called GenerateReport. Depending on the report type we instantiate either PDFReportWriter or ExcelReportWriter and call the respective methods of the class. Note that I am not really worry about the object oriented features and code optimization here. We can use factory or abstract factory pattern here to remove the conditional and duplicated code. Since it is outside the scope of this I’ll leave it as is.

If we use this approach it will work. But there are minor flaws here which can cause problems. All the methods WriteHeader, WriteReportContents and WriteFooter are public methods of PDFReportWriter and ExcelReportWriter. If we look at the requirements, we should have the header first then the contents and finally the footer. Imagine what can happen if the developer who uses these classes calls the method in some other order.

Another case can be when some developer forgets to use one or more method. For example in the above client code for PDF report generation, the developer can completely forget to make a call pdfReportWriter.WriteFooter().

How can we make sure that the report is generated correctly with all the details? This is where the Template Method pattern comes into the picture. It defines the structure of an algorithm into a method and allows the subclasses to provide the specific implementations. Lets see how we can refactor our code to make use of Template Method Design Pattern.

Refactored Solution with Template Method Design Pattern

The steps of our algorithm in this case are the rendering of three blocks of the report. We want to ensure that three blocks Header, Contents and Footer are always rendered in the same order in both the reports. We define a abstract class which is used to define a method. This method defines the steps of the algorithm. Lets see how.

    public abstract class ReportWriter

    {

        public void WriteReport()

        {

            WriteHeader();

            WriteReportContents();

            WriteFooter();

        }

 

        public abstract void WriteFooter();

 

        public abstract void WriteReportContents();

 

        public abstract void WriteHeader();

    }

ReportWriter is an abstract class. I have encapsulated the report writing into a method called WriteReport and defined the steps of report generation inside this method. Both the PDFReportWriter and ExcelReportWriter inherit from this abstract class and override the methods. After this refactoring, the client code becomes very simple. We need to call only one method instead of calling individual methods.

        public void GenerateReport(ReportType reportType)

        {

            ReportWriter reportWriter = null;

 

            switch (reportType)

            {

                case ReportType.PDF:

                    reportWriter = new PDFReportWriter();

                    break;

                case ReportType.EXCEL:

                    reportWriter = new ExcelReportWriter();

                    break;

            }

 

            if (reportWriter != null)

            {

                reportWriter.WriteReport();

            }

        }

A small refactoring makes the client code even more easier. What this refactoring has enabled us to do is modify the report generation without impacting the client code. Assume that in future, the business users decide to add grouping functionality to the report. We can define another abstract method in the abstract class and the derived classes can provide their own implementations of rending the grouped data.

Usage of Template Method within DotNet Framework

One of the most common example where Template Method is used within DotNet framework is the ASP.NET. The lifecycle of an ASP.NET Page follows a set of events. The application developer can override the events as per their needs to customize the behaviour of the page. The framework provides a default implementation for some of the events which can be overridden by developers.

Apart from the ASP.NET page lifecycle, the server controls also makes use of the Template Method pattern. If you have used data bound controls like DataGrid, Repeater etc you can customize various templates like HeaderTemplate, RowTemplate, FooterTemplate. Almost all server controls make use of the Template Method pattern. ASP.NET or other DotNet technologies like Winforms, Silverlight, WPF etc provide templates with default implementations.

One example of default implementation is the way ViewState is managed in the Webforms. The default implementation stores the viewstate data into a hidden field inside the html page that is rendered to the browser. We can override the LoadViewState and SaveViewState methods to store the view state into data base or the Web server.

We can also have scenarios where the default implementation does nothing. In such cases we can call the methods which are invoked from with the template method algorithm as hooks or placeholders. In the default implementation, they don’t do anything. But they can be overridden in the derived classes to provide custom behaviour. We can see examples of this in the Pre and Post processing events in the ASP.NET page life cycle.

Conclusion

The example I used here related to report writing is somewhat similar to the one used during Abstract Factory design pattern. One thing we need to understand while using design patterns is their intent. We might think couple of patterns are almost same in the way they behave by looking at the UML diagram. But the main point which helps us in pin pointing the pattern to use is the intent of the pattern.

In case of Template Method Design Pattern, the intent is to abstract the algorithm into a method and let the subclasses override the actual behaviour. Template method is used when we have certain steps common in different representations of an algorithm. It can also be used to provide “Hooks” or “placeholders” for operations which might not be necessary for all the different implementations.

As always the complete solution can be downloaded.

Until next time Happy Programming.

Further Reading

Here are some books I recommend related to the topics discussed in this bog post.

spacer

Design Patterns And Enterprise Patterns

Design Patterns are solutions to the recurring problems. There are different types of patterns. The most basic ones are the Design Patterns. Then there are higher level patterns like Enterprise Design Patterns. We can classify patterns  based on different criteria. The classic Gang of Four Design Patterns (GoF) are the foundation for recurring software problems. These consists of 23 patterns which mostly deal with the low level design of software. These patterns are solutions or in fact templates for making the code more and more reusable and maintainable. One of the primary goals of design patterns is to make the software easy to modify and maintain without making large scale changes. Hence most of the Gang of Four patterns talk about adapting the software to new requirements without major modifications to the existing software. They are more into making the software flexible to adapt to new changes.

Martin Fowler and various other prominent software professionals came up with next level of patterns which don’t necessarily deal with how we design the classes and interfaces. But their patterns were based on how we use the components in broader sense. They defined the Enterprise Architectural Patterns. These patterns deal with commonly used solutions across enterprises. These patterns are still evolving and unlike the GoF patterns their origins are in different places.

Architectural patterns are based on the type of choices people make while designing or integrating their solutions. Some of the Architectural patterns are Service Oriented Architecture (SOA), REST etc. These patterns basically define how we are going to build the complete system by integrating smaller components within the scope of the application. When some one says they are following SOA, we can be sure that the business logic is abstracted into a service layer and the user interface interacts with the service for carrying out various business processes. Similarly when we hear people talking about RESTful API we know that they are taking about a commonly used REST protocol for referencing the resources over the internet.

Enterprise Architectural Patterns are another set of patterns which deal with the common solutions to recurring problems in an enterprise applications. These are collection of patterns which deal with different aspects of enterprise application. Some of the examples of enterprise patterns are using Dependency Injection and Inversion of Control container to loosely couple different components of the application. Using an Object Relational Mapper (ORM) to map entities between relational database and the business objects. Abstracting cross cutting concerns using Aspect Oriented Programming. The set of enterprise patterns are divided by different components which are used within the enterprise applications like the front end or view, middle tier or business layer and backend or persistence layer. For more details you can refer to the excellent book by Martin Fowler.

Here is my attempt to share my understanding about the patterns I have used during my professional career. Many of the examples found on the internet are very very elementary and not related to real world applications. Here is my attempt to explain various patterns as close as possible in a way they are used in real world applications. Here is a collection of posts related to Design Patterns & Enterprise Patterns I have written so far.

Design Patterns

Strategy Design Pattern – This post demonstrates how to refactor conditional code into Strategy pattern implementation using monthly instalment for loan calculator as an example.

Factory Pattern – Using account statement dispatcher as an example this post demonstrates the how to refactor the object creational logic into a factory.

Singleton Design Pattern – Demonstrates 3 different ways of implementing Singleton Design Pattern.

Abstract Factory Design Pattern – Implementation of abstract factory using report writer as an example.

Adapter Design Pattern – An example of Adapter Design Pattern using social network client as an example.

Template Method Design Pattern – Using report writer in different format like PDF and Excel, this post demonstrates the use of Template Method Design Pattern.

Observer Design Pattern uses Portfolio Manager as an example showing how Stocks (Subject) can notify Observers like grid and pie chart about the state changes.

Observer Design Pattern with Delegates And Events demonstrates the Portfolio Manager solution refactored from earlier post using Delegates and events capabilities of C# language. 

Prototype Design Pattern – Using an example of Store creator this demo shows how to simplify the object creation using prototype Design pattern

Decorator Design Pattern – Based on the concept of an order manager with various combinations like domestic orders or international orders including shipping, gift wrapping, personalizing as additional attributes, this post demonstrates the use of Decorator Design Pattern.

State Design Pattern – Using Personal loan as an example this post demonstrates the use of State Design Pattern to depict how the behaviour of an object changes based on the internal state of an object.

Facade Design Pattern – Using housing loan as an example, this post demonstrates the use of Facade pattern to simplify the various sub-systems used to verify different details.

Builder Design Pattern – This post demonstrates the use of Builder pattern using a bill generation as an example.

Composite Design Pattern – Uses an example of profit calculator at different levels like Store, State, City etc. to demonstrate the Composite Design Pattern.

Enterprise Patterns

Specification Pattern – Specification pattern implementation using LINQ. This post demonstrates the use of specification pattern to filter a products collection based on various attributes like Color, Price etc.

Recommendations

Here are some books I recommend related to the topics discussed in this blog post.

spacer