Skip to main content

Posts

Showing posts from February, 2012

Factory Design Pattern

In the previous post I had mentioned about Factory Design Pattern. We already had an implementation alongside the Strategy Design pattern. In this post I would like to talk in detail about the Factory Design Pattern. The primary use of factory pattern is to encapsulate the object creation logic from the client. Factory pattern is a creational pattern which helps decoupling the consumers of a class from creating a new instance. Every time we use a new keyword we are tightly coupling the class and its consumer. Factory pattern is also useful when we have a common interface from which we can choose one of the option to create an instance.Problem StatementAssume that we are building software for a bank. Customers of the bank are entitled to receive the account statement. They can choose the mode of delivery for the statement. It can be a physical statement or an electronic account statement. Based on the customer preference the account statement will be delivered to the customer either in…

Strategy Design Pattern

Design patterns are reusable solutions to repetitive problems. On various occasions I have seen people writing conditional code. Design patterns help in modularizing the code and making it extensible and maintainable. This post is about how we can refactor conditional logic to better maintainable and cleaner solution using Strategy Design Pattern.Problem statementImagine we have to calculate the monthly instalment for a loan. The loan can be of various types for e.g. home loan, car loan, personal loan etc. Each loan can have different duration and also different interest rates. Based on these factors the equated monthly instalments (EMI) will be different. Lets look at a solution without using design patterns and try and refactor the same to one using design patterns.For this hypothetical example lets consider that the interest rates for home loan is 10% and car loan is 8%. So we can start building the code to compute the EMI. Lets assume that in both the car and home loan cases the a…