Category Archives: Design Patterns

Builder Pattern

You must have used DocumentBuilder or StringBuilder classes if you have worked with core Java. Buider pattern is simple object creation pattern, which helps handling of creation of complex objects by breaking the object building exercise into multiple easy steps.

A simple example will be- let’s say we have a car object with many complex properties- Engine, top speed, boot_space, seating arrangement, air_conditioning etc. A CarBuilder class can help in creation of the objects

Class CarBuilder{

public void setEngine(Engine e)
{
//..
}

public void setSpeed(String s)
{
//..
}

public void setAirConditioning(String temp, String cooling, int avgtemp)
{
//..
}

public Car getCar()
{
//This will finally create the car object and return
}

}

The calling method

CarBuilder cB=new CarBuilder();
cB.setEngine(e);
//.so on
Car myCar=cB.getCar();

To make it more useful in handling higher complexity, we can create the CarBuilder as Abstract Class or interface, which is implemented by HatchBackBuilder, SportsCarBuilder etc.

Prototype pattern

Prototype is a creational design pattern. When I first read about it, I got it a bit confused with Factory pattern. If you look at Car Factory example, where the factory helps us create a “new” car at run time, and we can choose whether we want a Sedan or Hatchback while the car creation. Prototype pattern differentiates itself from factory pattern, by providing prototypes of objects beforehand, and creating a copy at runtime.

Extending our Carfactory example further, lets say now we are not limited to 2 set of cars, but we have ready prototypes say a car called Swift, Ritz, Figo, Scorpio, all with their specifications already defined. At runtime, we will just create a copy or clone of the car which user needs. Note that we can actually build our prototype pattern on factory pattern, but for simplicity of this example we will stick to a simple implementation of car by these objects.

public class CarPrototype{

Car swift=new Car();
swift.setMaxSpeed(200);
swift.setMileage(20);
swift.setFuel(Diesel);

Car figo=new Car();
//set properties

//more cars

//we will also override clone method if required

public Car getCarFromPrototype(String str)
{
switch(str)
{
case ‘FIGO’: return figo.clone();break;
case ‘SWIFT’: retrun swift.clone();break
//so on
}
}

}

One important difference between factory and prototype is that prototype pattern creates a clone and factory pattern create a new object. When a new object is created using a new keyword, it makes sure that user get a object with fresh state. Whereas in clone (prototype), we are making sure that we are also copying a particular state of object. This also helps us understand when to use factory and when prototype should be preferred.

Abtract Factory Pattern

Abstract Factory pattern is another creational design pattern in the league of Factory, Singleton, builder and Prototype patterns. The term has some resemblance to Factory pattern and so does implementation. I tried looking around the internet to figure out some good explanation, but unfortunately they are too complex. This will help though- http://www.oodesign.com/abstract-factory-pattern.html

In my attempt to over simply things, I will try to go back to factory pattern and the example I used for CarFactory, http://kamalmeet.com/2013/06/factory-pattern/. The idea was simple with CarFactory, that user knows he wants a car, but which car is to be created is decided at runtime.

factory

AbstractFactory Extends the idea a bit further, it gives us a factory of factories.

AbstractFactory

To understand the above diagram, lets extend our CarFactory example, lets say we know that we need a vehicle to start with but we do not know if it will be a car or a bike (decided at runtime). So we will have 2 concrete factories-  CarFactory and BikeFactory. CarFactory is responsible for creating Sedan or HatchBack as previous example and BikeFactory is creating SportsBike and NormalBike. On top of the concrete factories we will introduce a AbstractVehicalFactory which is implemented by CarFactory and BikeFactory.

Factory Pattern vs Strategy Pattern

Factory pattern and Strategy pattern might create a confusion if you are using them for the first time. Atleast I was confused, so I tried to analyze the two patterns further.

Let’s relook at the two examples which we used for factory and strategy pattern.

http://kamalmeet.com/2013/06/factory-pattern/

http://kamalmeet.com/2013/03/understanding-strategy-pattern/

Car Factory- A factory for creating Sedan or Hatchback car at the run time based on user need.

Tax Calculator- To pick at run time which type of tax to be calculated (Indian or German).

The difference lies in the usage of two examples above. In first example we are creating object of something, so we can conclude factory pattern is a creational pattern. In second example it is clear we are trying to achieve a goal / execute a method based on input, hence strategy pattern is an operational pattern.

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