Thursday, April 21, 2011

Creational Patterns : Prototype

Creational Patterns : Prototype (Make new objects by cloning the objects which you set as prototypes)


When to use ?

Prototype design is one of the design pattern under creational design pattern. This pattern describes how to clone object. Whenever application doesn’t need to create new object or object creation is more expensive than cloning will help to resolve.


Example:

We will consider Product example where we can clone product with Book and Cloths Classes.Product.java is a abstract java class which implements Cloneable interface. Class ’title’ & ‘price’ and there getter & setter methods and also implemeted clone() method. This method creates and return the copy of the super class.


/**
*
* @author R.Amirtharaj
*/
public abstract class Product implements Cloneable {
private String title;
private String price;
public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getPrice() {
return price;
}

public void setPrice(String price) {
this.price = price;
}

public Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}

Book.java and Cloths.java extends Product and having separate variables author & size which have getter and setter methods in it.

/**
*
* @author R.Amirtharaj
*/
public class Book extends Product {
private String author;

public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}

/**
*
* @author R.Amirtharaj
*/
public class Cloths extends Product {
private int size;

public int getSize() {
return size;
}

public void setSize(int size) {
this.size = size;
}
}

ProductFactory.java is the factory where it will produce the products and adding in HashMap based on key as product title and value as product.

/**
*
* @author R.Amirtharaj
*/

public class ProductFactory {
private static Hashtable productMap = new Hashtable();

public static Product getProduct(String productCode) {
Product cachedProduct = (Product) productMap.get(productCode);
return (Product) cachedProduct.clone();
}

public static void loadCache() {
Book book = new Book();
book.setTitle("Java best practices");
book.setAuthor("Amirtharaj");
book.setPrice("1000");
productMap.put(book.getTitle(), book);
Cloths cloths = new Cloths();
cloths.setTitle("Jeans");
cloths.setSize(32);
cloths.setPrice("450");
productMap.put(cloths.getTitle(),cloths);
}
}


Demo.java is product outlet, which will load the cashe from the ProductFactory by calling ProductFactory.loadCache(); and clone the product by getting the product from ProductFactory


/**
*
* @author R.Amirtharaj
*/
public class Demo {
public static void main(String[] args) {
ProductFactory.loadCache();

Book clonedBook = (Book) ProductFactory.getProduct("Java best practices");
System.out.println("Product cloned as Book");
System.out.println("Title = " + clonedBook.getTitle());
System.out.println("Author = " + clonedBook.getAuthor());
System.out.println("Price = " + clonedBook.getPrice());

System.out.println("Product cloned as Cloths");
Cloths clonedCloths = (Cloths) ProductFactory.getProduct("Jeans");
System.out.println("Title = " + clonedCloths.getTitle());
System.out.println("Size = " + clonedCloths.getSize());
System.out.println("Price = " + clonedCloths.getPrice());
}
}

Advantage of prototype design pattern

Adding and removing objects at runtime
Creating cloned object based on the values
It reduced the inheritance of the class (sub classing)


Usage of prototype design pattern

When the classes to instantiate are specified at run time.
When you want to avoid building a class hierarchy of factories that parallels the class hierarchy of products.
When instances of a class can have one of only a few combinations of state.

Creational Patterns : Builder Pattern

Creational Patterns - Builder Pattern (Make and return one object various ways)


When to use ?

Builder patten will divide complex in to simple steps. Its nothing but building complex object by simple objects. Its kind of building complex objects in to step by step simple objects.

Example :

Need to build specifications details of cars for specific brand . Lets take example as we need to build specification details for AudiS6 and AudiS7.

I will show in java example how to build car specifications

First need to create Car object this is contains specifications of a car product. It is a POJO object.

/**
*
* @author R.Amirtharaj
*/
public class Car {

public boolean isPowerSteering() {
return powerSteering;
}

public void setPowerSteering(boolean powerSteering) {
this.powerSteering = powerSteering;
}

public double getPrice() {
return price;
}

public void setPrice(double price) {
this.price = price;
}
private double price;
private boolean powerSteering;

@Override
public String toString()
{
String output = "";
output += ("Price = "+price+"\n");
output += ("powerSteering = "+powerSteering+"\n");
return output;
}
}

Now we are going show Car Builder abstract builder class.

/**
*
* @author R.Amirtharaj
*/
public abstract class CarBuilder
{

protected Car car;

public Car getCar() {
return car;
}

public void createNewCar() {
car = new Car();
}

public abstract void setPowerSteering();

public abstract void setPrice();
}


The above java program show abstract builder class contains 2 abstract function which need to be implemented in derived class.
Below example shows how to create concrete class by extending car builder abstract class. We will create AudiS6 & AudiS7 concrete classes

which extends CarBuilder abstract builder class.

Concrete AudiS6 class

/**
*
* @author R.Amirtharaj
*/
public class AudiS6 extends CarBuilder
{

@Override
public void setPowerSteering() {
car.setPowerSteering(true);
}

@Override
public void setPrice() {
car.setPrice(2500000);
}

}


Concrete AudiS7 class

/**
*
* @author R.Amirtharaj
*/
public class AudiS7 extends CarBuilder
{

@Override
public void setPowerSteering() {
car.setPowerSteering(true);
}

@Override
public void setPrice() {
car.setPrice(3000000);
}

}

Now we all set ready by building small building blocks. Now we need to create Specifications director which will build the provided car

specifications.

Below is java code for Specifications director class

/**
*
* @author R.Amirtharj
*/
public class Specification {

private CarBuilder carBuilder;

public void setCarBuilder(CarBuilder aCarBuilder) {
carBuilder = aCarBuilder;
}

public Car getCar() {
return carBuilder.getCar();
}

public void constructSpecifications() {
carBuilder.createNewCar();
carBuilder.setPowerSteering();
carBuilder.setPrice();
}
}


Everything is created. Now we can create example of AudiS6 and AudiS7 car specification builder patten.
Below is example for creating specifications for AudiS6 and AudiS7

/**
*
* @author R.Amirtharaj
*/
public class Demo {

public static void main(String arg[])
{
Specification spec = new Specification();

CarBuilder audis6 = new AudiS6();
CarBuilder audis7 = new AudiS7();

// Specification for AudiS6
spec.setCarBuilder(audis6);
spec.constructSpecifications();
Car audis6_car = spec.getCar();
System.out.println("Specifiction for AudiS6");
System.out.println(audis6_car.toString());

// Specification for AudiS7
spec.setCarBuilder(audis7);
spec.constructSpecifications();
Car audis7_car = spec.getCar();
System.out.println("Specifiction for AudiS7");
System.out.println(audis7_car.toString());

}
}


Usage of builder patten in real time

* Build the complex objects by specifying there behavior and specifications . This object will be used as wrapper for constructing of building objects.
* It will avoid process of building complex objects form

Wednesday, April 13, 2011

Design Pattern : Abstract Factory Pattern

Creational Patterns - Abstract Factory Pattern ( Sets of methods to make various objects )

This pattern is one level of abstraction higher than factory pattern. This means that the abstract factory returns the factory of classes.

Like Factory pattern returned one of the several sub-classes, this returns such factory which later will return one of the sub-classes.

When to use ?
One of the main advantages of Abstract Factory Pattern is that it isolates the concrete classes that are generated. The names of actual implementing classes are not needed to be known at the client side. Because of the isolation, you can change the implementation from one factory to another.


Example :

Suppose we need to get the specification of various parts of a computer based on which work the computer will be used for. The different parts of computer are, say RAM and Processor. The different types of computers are PC and Server.

So, here we have an abstract base class Computer.

/**
*
* @author R.Amirtharaj
*/
public abstract class Computer {
public abstract Parts getRAM();
public abstract Parts getProcessor();
}


This class, as you can see, has three methods all returning different parts of computer. They all return a method called Parts. The

specification of Parts will be different for different types of computers. Let’s have a look at the class Parts.

/**
*
* @author R.Amirtharaj
*/
public class Parts {

private String specification;

public Parts(String specification) {
this.specification = specification;
}

public String getSpecification() {
return specification;
}
}

And now lets go to the sub-classes of Computer.

/**
*
* @author R.Amirtharaj
*/
public class PC extends Computer {

/**
* Method over-ridden from Computer, returns the Parts ideal for
* PC
* @return Parts
*/
public Parts getRAM() {
return new Parts("512 MB");
}

/**
* Method over-ridden from Computer, returns the Parts ideal for
* PC
* @return Parts
*/
public Parts getProcessor() {
return new Parts("Celeron");
}
}



/**
*
* @author R.Amirtharaj
*/
public class Server extends Computer {

/**
* Method over-ridden from Computer, returns the Parts ideal for
* Server
* @return Parts
*/
public Parts getRAM() {
return new Parts("4 GB");
}

/**
* Method over-ridden from Computer, returns the Parts ideal for
* Server
* @return Parts
*/
public Parts getProcessor() {
return new Parts("Intel P 4");
}
}

Now let’s have a look at the Abstract factory which returns a factory “Computer”

/**
*
* @author R.Amirtharaj
*/
public class Demo {

public static void main(String arg[])
{
Demo abstarcfactorydemo = new Demo();
Computer pc = abstarcfactorydemo.getComputer("PC");
System.out.println("PC Specification ");
System.out.println("RAM = "+pc.getRAM().getSpecification());
System.out.println("Processor ="+pc.getProcessor().getSpecification());

Computer server = abstarcfactorydemo.getComputer("Server");
System.out.println("Server Specification ");
System.out.println("RAM = "+server.getRAM().getSpecification());
System.out.println("Processor ="+server.getProcessor().getSpecification());
}

public Computer getComputer(String computerType) {
Computer comp = null;
if (computerType.equals("PC")) {
comp = new PC();
} else if (computerType.equals("Server")) {
comp = new Server();
}
return comp;
}
}

Monday, April 11, 2011

Design Pattern : Factory Pattern

Creational Patterns - Factory Pattern ( Methods to make and return components of one object various ways):


When to use ?

If we have a super class and n sub-classes, and based on data provided, we have to return the object of one of the sub-classes, we use a factory pattern.

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. In programmer’s language (very raw form), you can use factory pattern where you have to create an object of any one of sub-classes depending on the data provided.


Example:

Below Example have Person as a Super class and Male and Female extends Person.Finally in main program we can create person object based on Male or Female.


/**
*
* @author R.Amirtharaj
*/
public class Person {

// Name of the Person
private String strName;
// Gender : M or F
private String strGender;

public String getStrGender() {
return strGender;
}

public void setStrGender(String strGender) {
this.strGender = strGender;
}

public String getStrName() {
return strName;
}

public void setStrName(String strName) {
this.strName = strName;
}

}



/**
*
* @author R.Amirtharaj
*/
public class Male extends Person {

public Male(String strName) {
System.out.println("Hello Mr. " + strName);
}
}

/**
*
* @author R.Amirtharaj
*/
public class FeMale extends Person {

public FeMale(String strName) {
System.out.println("Hello Ms. " + strName);
}
}

/**
*
* @author R.Amirtharaj
*/
public class Demo {

public static void main(String args[]) {
Demo factoryDemo = new Demo();
factoryDemo.getPerson(args[0], args[1]);
//factoryDemo.getPerson("Amir", "M");

}

public Person getPerson(String strName, String strGender) {
if (strGender.equals("M")) {
return new Male(strName);
} else if (strGender.equals("F")) {
return new FeMale(strName);
} else {
return null;
}
}
}

Friday, April 8, 2011

Design Pattern : Singleton Pattern

Creational Patterns - Singleton Pattern(A class distributes the only instance of itself)



When to use ?
There are some instances in the application where we have to use just one instance of a particular class.


Below Example, Display and FDisplay Class having printwithDateandTime method , it will print with currentTime

APPROACH 1:
We use Singleton pattern for this and instantiate the Display when the first request hits

import java.sql.Timestamp;
/**
*
* @author R.Amirtharj
*/
public class Display {

// singleton - pattern
private static Display display = null;

public static Display getDisplay() {
return display;
}

// initialises the display, creates an object
public static void initialize() {
if(display == null) display = new Display();
}

/**
* Private constructor
*/
private Display() {
display = this;
}

public void printwithDateandTime(String strMsg)
{
System.out.println(strMsg+" Date:"+new Timestamp(System.currentTimeMillis()));
}
}

APPROACH 2:
Create a class and declare it as “final” with all the methods “static”. In this case, you can’t create any instance of class and can call the static methods directly.


import java.sql.Timestamp;

/**
*
* @author R.Amirtharj
*/
public final class FDisplay {
public static void printwithDateandTime(String strMsg)
{
System.out.println(strMsg+" Date:"+new Timestamp(System.currentTimeMillis()));
}
}


Main Class:


/**
*
* @author R.Amirtharaj
*/
public class Demo {

public static void main(String arg[])
{
// Approach 1
Display.initialize();
Display.getDisplay().printwithDateandTime(" Singleton test Approach 1 ");

// Approach 1
FDisplay.printwithDateandTime(" Singleton test Approach 2");
}

}

Note : The advantage of this static approach is that it’s easier to use. The disadvantage of course is that if in future you do not want the class to be static anymore, you will have to do a lot of recoding.