Tag Archives: Design Patterns

Factory Pattern

Factory Pattern is one of the highly used design patterns. The reason being , its genuine usefulness and closeness to real world. Let’s take a very simple real world example to get started, and then we will map it to the pattern.

Let’s say we have a Car factory which creates many types of cars. To keep it simple, let’s say it creates 2 type of cars- hatchback & sedan. These two type of cars will have many similar attributes like top speed, power steering etc. but there will be some features explicit to type of car (say a back seat AC or TV is available only for sedan cars). What will be a natural Object Oriented Design for this arrangement?

Class Car Extended by Class Sedan and Class HatchBack

If you know what type of car you need beforehand, we are good. But in case you need to create the car at runtime, say on user input, you will need some helper class which will create specific type of car at runtime. This class is our factory class.

factory

Class CarFactory

{

Public static Car getCar(String carType){

If(carType.equals(“sedan”)) return new Sedan();

else return new HatchBack();

}

}

A better example in technical terms might be that your application supports multiple database types (say on test environment you use MySql whereas on production you have Oracle). A DataBaseConnectionFactory can help you get connection of specific type of database at runtime (say reading the database type value from some property file.

 

Singleton Pattern Round Up: All about singleton pattern

Here is summary of what I have written so far on singleton patterns. The examples taken here are mostly from Java.

Singleton Pattern #1: Basics, Definition, Usage
Gives a basic idea of singleton pattern is all about.

Singleton Pattern #2: Lazy vs Eager Instantiation for a Singleton Class
The difference between two types of instantiations, and which one is better under what circumstances.

Singleton Pattern #3: Problems with Singleton, Thread-Safe Singleton Class
Issues with using singleton, how to make your singleton classes threadsafe.

Singleton Pattern #4: Difference between Singleton and Static classes
Sometimes people confuse between singleton and static classes. When should one use them and why?

Singleton Pattern #4: Difference between Singleton and Static classes

The basic differences between singleton and static classes (when we say  static class in java, it is a class with static members) in nutshell are:

1. Singleton classes can hold instance variable while static can’t
2. Singleton classes can be inherited
3. Static classes are more useful while handling the stateless data
4. At a later stage if you think that you need more instances of a singleton class, you can simply modify the class. Basically make the constructor public/ make the singleton class non-singleton, depending on your requirement
5. For simple functionalities where we need utility methods to be implemented on some data and simple return statements, static classes are of better help. For example, creating a string utility or math utility class which have methods like sqare (takes an integer say 2 and return 4 ), cube (takes 2 and simply returns 8 )

Singleton Pattern #3: Problems with Singleton, Thread-Safe Singleton Class

A side effect of using singleton class: as the constructor of the singleton class is private, you cannot create a subclass of a singleton class, but in most of the cases that is desirable. Additionally you can declare the class as final to explicitly show that the class can’t be subclassed. But in case if it is required to create a subclass of singleton class one can define the constructor of singleton class as protective instead of private.

Another point to note is that the singleton classes are not thread-safe. Simply putting it if the two threads enter the

If(instance==null)
{
//create new instance.
}

block simultaneously, it will create two different instances of the class. This is an undesirable condition and cause unwanted behavior in the application. Also note here that in case of eager instantiation this problem does not occur as the instance gets created beforehand.

Making your singleton class thread-safe is easy, you just have to make your getinstance method synchronized.

Public synchronized static singletonExample getInstance()
{
//if instance is null create else return old instance
}

Originally posted February 15, 2007

Brought back using archive.org

Singleton Pattern #2: Lazy vs Eager Instantiation for a Singleton Class

This post is in continuation to my previous post where I discussed about basics of singleton pattern. The kind of instantiation mentioned in that post, where we create an instance of singleton class only when it is called for the first time is called lazy instantiation. Another variation can be creating the instance before it is called, this kind of instantiation is called eager instantiation

Public Class singletonExample {
private static singletonExample instance=new singletonExample();
private singletonExample{
// no instantiation is possible
}

public static singletonExample getInstance()
{
return instance;
}
}

If you look carefully, here we are using

private static singletonExample instance=new singletonExample();

to initialize the object ‘instance’ rather than setting it as null initially. And in our getInstance() method we are just returning the ‘instance’ without any checks. So the advantage in this case is that we are saved making one check everytime getinstance is called. One apparent disadvantage is that in this case the instance of singletonExample will always be present whether it is called or not.

Originally posted February 13, 2007

Brought back using archive.org

Singleton Pattern #1: Basics, Definition, Usage

Singleton pattern: As the name suggests, a singleton pattern refers to a pattern where you need only a ’single’ instance of a class to be present. The examples can be windows manager where you want only one window to be active at a time or a file read write where only one method should be updating a file at a time.

Here is a skeleton example of a singleton class:

Public Class singletonExample
{
private static singletonExample instance=null;
private singletonExample{
// no instantiation is possible
}

public static singletonExample getInstance()
{
if (instance==null)
{
instance=new singletonClass();
}
return instance;
}
}

the caller class

public class singletonUser{
singletonExample singletonInstance= singletonExample.getInstance();
}

Explanation:

Here singletonExample is our singleton class. In the first line we have created an instance of this class as null. We have declared a private constructor for the class to make sure that no object of class can be created outside the class.

getInstance() method is the entry point for the class which will return the only instance present for the class. This method is marked as static as it will be called directly from other classes. In this method we check if the instance of singletonExample is already present, if yes, return that instance else create the instance and return it. This makes sure that only one instance of the class is present at any point.

In the user class, that is calling our singleton class, we just need to call our singletonExample.getinstance() method which will return us the instance of singletonExample.

Originally posted February 13, 2007 at 2:10 pm

Brought back using archive.org

Facade Pattern

Façade pattern is a simple design pattern which is used to hide unwanted details for a module. Chances are that you have followed this pattern without even knowing that you are using it.

The literal meaning of Façade is front; that explains a lot about pattern. I have a habit of over simplifying things, so I will do the same here using a simple example. Say you need to fill up some forms to get admission to a college or club. There is a procedure to do that, first you need to go to clerk 1 and fill general info form, second you need to go to clerk 2 and fill a form for specific interests / courses. Than you need to go to third one for background check form and finally you need to get to fourth clerk for filling fees details.

Will it not be good if we could have done all this at one place in one form. Say there is a receptionist at front desk who takes all these details from you and is responsible for contacting all the clerks and getting details filled (obviously you are not aware of the clerks’ existence as you are only interacting with receptionist). That saves you from a lot of trouble and also helps institution to keep the direct dependency low. Say if they are changing location of a clerk, in first case they would need to tell hundreds of users about the change so that they can go to correct location, but in second case they are only telling the receptionist.

In above solution we are following façade pattern (to solve a real life problem). In software term the same stands true. Say you are interacting with this college system, earlier you were to fetch data from multiple classes which can be done from one façade class. Secondly maintenance is easy as background changes (change clerk location) will need a change only in façade class and no change for users using the API.

Case Original:

GeneralInfo generalInfo=new GeneralInfo();

GeneralInfo.fillInfo(MyDetails);

CourseInfo courseInfo=new CourseInfo();

CourseInfo.fillInfo(MyDetails);

Fees fees=new Fees();

MyDetails.receipt=fees.fillFees(MyDetails);

MoreInfo moreInfo=new MoreInfo();

enrollmentNumber= moreInfo.finallyFill(MyDetails);

Case Facade Pattern:

CollegeFacade collegeFacade=new CollegeFacade();

enrollmentNumber=collegeFacade.fillInfo(MyDetails);

Facade Pattern

Understanding Strategy Pattern

Let’s first try to understand what a strategy is. In simple worlds a strategy is a plan (for something). Or a little more elaboration “a plan, method, or series of maneuvers or stratagems for obtaining a specific goal or result”.

For purpose of understanding, let’s take a simple example. Say we want to create a piece of code to calculate the tax for a given salary. An added complexity is that code should work for multiple countries. All these countries will have different strategy (formula) for tax calculation. Based on the country provided as input, we will need to change our strategy for tax calculation at the run time.

So how does strategy pattern help us? Let’s solve the above mentioned problem with tax calculation to make it clear.

Strategy Pattern

The above image makes it clear. We have 2 strategies to calculate tax, one for India and other for Germany. While initializing the strategy pattern class object(TaxCalculator), we will define which strategy is to be followed.

TaxCalculator taxCalculator(new IndiaTaxStrategy());
taxCalculator.calculateMyTax();//calculateMyTax will simply call the parent class calculate tax method with the income

Spring Implementation of Dependency Injection

In last post I explained what is dependency injection (DI). Now I will focus on how the concept is implemented in Spring framework. If we are clear on the concept of DI, remaining is piece of cake.

There are 2 ways to implement DI in Spring

1. Using annotations

Spring is basically annotation driven language (see here). @Autowired is the annotation which will help us inject dependencies in Spring. @Autowired will tell the code to look for given object somewhere in code. The dependency injection can be implemented in 3 ways

a. Using my previous Employee- Address example for dependency injection, adding address dependency through constructor

Class Employee

{

public Address address;

public String name;//other stuff

@Autowired
Employee(Address address)
{
this.address=address
}

}

And In application context xml add

<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

	<bean id="EmployeeBean" class="com.test.Employee">
		<property name="name" value="kamal" />

	</bean>

	<bean id="AddressBean" class="com.test.Address">
           <property name="street" value="43rd" />
		<property name="apt" value="29" />
		<property name="city" value="New york" />
	</bean>

b. using Setter- similar to constructor

Class Employee

{

public Address address;

public String name;//other stuff

Employee()
{
}

@Autowired
public void setAddress(Address address)
{
this.address=address;
}

}

c. Using Field

Class Employee

{
@Autowired
public Address address;

public String name;//other stuff

Employee()
{
}

}

2. Using XML configuration (application context)

Same as above (almost), we will not use @Autowired but add the dependency in the xml itself

<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

	<bean id="EmployeeBean" class="com.test.Employee">
		<property name="name" value="kamal" />
<property name="address" ref="AddressBean" />

	</bean>

	<bean id="AddressBean" class="com.test.Address">
           <property name="street" value="43rd" />
		<property name="apt" value="29" />
		<property name="city" value="New york" />
	</bean>

Finally to run your example add these lines to code

ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {“SpringBeans.xml”});

Customer cust = (Customer)context.getBean(“EmployeeBean”);

Further References

http://www.vogella.com/articles/SpringDependencyInjection/article.html

http://www.mkyong.com/spring/spring-auto-wiring-beans-with-autowired-annotation/

More on Dependency Injection

Sometime back I talked about dependency injection. Dependency injection is a design pattern that implements inversion of control principal. That is, you take out a dependency from within a class and inject it from outside.

So lets say there are 2 classes, Employee and Address, say Employee is dependent on Address

Class Employee

{

public Address address;

public String name;//other stuff

Employee()

{

address=new Address(‘some values here’);

}

}

Here we are leaving the responsibility of creating the address with Employee class. Using DI (Dependency Injection) we will pull out this responsibility of creating the address object from Employee class and give it to calling/initializing class/container.

There are 2 ways to implement this DI concept

1. Through constructor:

class Employee{

public Address address;

Employee(Address address)

{

this.address=address;

}

}

2. Using a setter method:

Class Employee

{

public Address address;

public String name;//other stuff

Employee()

{

}

public void setAddress(Address address)

{

this.address=address;

}

}

Lets make it a bit more interesting. Say we have a AddressFactory which can create either a LocalAddress or PermanentAddress. Both LocalAddress and PermanentAddress implement Address Interface.

In case of non DI scenario

Class Employee

{

public Address address;

public String name;//other stuff

Employee()

{

//check if employee has local address

address=new AddressFactory.getAddress(“LocalAddress”);

//else case get permanent address

}

}

In this case DI becomes more useful as Employee class does not need to worry about the type of address which will be provided by calling class or container. No need to change the code given for DI implementation, it will work fine.