Creational Design Patterns in C# - Builder Pattern
Builder Pattern
Builder pattern (wiki) tries to separate the construction of a complex object from its representation. This pattern is used when complex object that need to be created is constructed by constituent parts that must by created in the same order or by using a specific algorithm.
Let’s consider this requirement You want to build a dashboard application for your user’s data. You want to give flexibility to your user to provide the data either in some flat file or Excel or in SQL database, whatever the end user is comfortable with. Builder pattern is good for such scenario. You first build an abstract class, say , implementing a method – lets say – . Then you build a Director class – lets call it – . This method can then call the method – paramDataSource.getDataFromSource – to get the data from whatever data source the parameter ‘paramDataSource’ is for, without worrying about the actual implemetion of complex logic involved in reading data from the three types of data source. The client application case class now shows three options to the user – FlatFile, Excel, or SQL; and based on what selection the user makes, creates the respective Builder class and passes it on as parameter to DashboardDirector’s ReadUserData method. After reading the data, the client application continues with the code to build and present the dashboard using that data. |
Here is a youtube video that perfectly explains Builder patter in a very simple way.
The Builder pattern may sound very similar to Factory pattern in theory. However there are some fundamental difference between the two. This SO post explains the difference.
← Prev: Creationl Design Pattern | Next: Factory Pattern → |