----

Saturday, September 28, 2013

Factory Design Pattern Example

Factory Design Pattern: The factory method pattern is an object-oriented creational design pattern. Factory Pattern deals with the problem of creating objects without specifying the class of object that will be created. 

Creating an object often requires complex processes, which is not appropriate to include within a composing object. The object's creation may lead to a significant code duplication and may not provide a sufficient level of abstraction. In an application if object creation code is spread in whole application, and if you need to change the process of object creation then you need to go in each and every place to make necessary changes.

Factory design pattern handles these problems by defining a separate method for creating the objects.
In simple words, if we have a super class and many sub-classes, and based on data provided, we need to return the object of one of the sub-classes, then we use a factory pattern.

This pattern introduces loose coupling between classes which is the most important principle one should consider and apply while designing the application. Loose coupling can be introduced by using abstract entities rather than concrete implementations.

When to use: The Factory patterns can be used in following cases:
1. When a class does not know which class of objects it must create.
2. A class specifies its sub-classes to specify which objects to create.
3. At run time you need to create an object based on input parameter...



Monday, September 23, 2013

Strategy Design Pattern Example


Strategy Design Pattern: Strategy pattern defines family of algorithms which are encapsulated and are interchangeable at run time depending on a factor that requires a particular algorithm to be executed. Strategy pattern encourages open-close design principle where a class is open for extension but closed for modification.

It is a suitable replacement for a if-else or switch-case statements or complex conditional logic within a method. It also leads to more testable code, especially when coupled with IOC.

When to use: Let us assume that you are a Telecom service provider and you provide prepaid recharge facility to the customer. Depending on the recharge amount you would like to provide free SMS and free Talk time offer.

The Telecom service system can have a TelecomOperator class. On each recharge this class has to determine different offer depending on the recharge amount....