Tuesday, May 12, 2009

Abstract Factory [Creational Pattern]

The Abstract Factory Method provides an interface to create and return one of several families of related objects. It provide an interface to create a family of related or dependent classes without specifying their concrete classes

Suppose you are writing a program to plan the layouts of the gardens. However no matter which kind of garden you are planning. Lets assumes garden can contains three types of plants
a. Border plants which would be planted on border side
b. Shaded Plants which would be planted for shading purpose
c. center Plants which would be planted on the center of garden

Lets code it. We have a base Garden class that contains main specifications of a garden of any type. So make it abstract.

public abstract class Garden {
public abstract Plant getBorder();
public abstract Plant getCenter();
public abstract Plant getShade();
}

Plant is a class that contains information about a plant of any type.

public class Plant {
private String name;
public Plant(String name) {
this.name = name;
}

public String getPlantName(){
return name;
}
}

Now in a real system, each type of garden would contains the plant information (infact a garden is a collection of many types of plant). Garden can of any type. Lets assumes there are three types of garden

first one is VegiGarden. Obviously this type of garden contains the features if Garden so :

public class VegiGarden extends Garden {

@Override
public Plant getBorder() {
return new Plant("Peas");
}

@Override
public Plant getCenter() {
return new Plant("Corn");
}

@Override
public Plant getShade() {
return new Plant("Neem");
}

}


next one is

public class AnnualGarden extends Garden {
@Override
public Plant getBorder() {
return new Plant("Bamboo");
}

@Override
public Plant getCenter() {
return new Plant("Mango");
}

@Override
public Plant getShade() {
return new Plant("Banyan");
}

}


and the last one is

public class FlowerGarden extends Garden {
@Override
public Plant getBorder() {
return new Plant("Rose");
}

@Override
public Plant getCenter() {
return new Plant("Carandola");
}

@Override
public Plant getShade() {
return new Plant("Popyi");
}
}


Now we have a GardenFactory that returns the object of requested garden type.

public class GardenFactory {
private String gardenType;
private String gardenName;

public GardenFactory(String gardenType) {
this.gardenType = gardenType;
if(gardenType.toUpperCase().equals("VG"))
gardenName="Vegitable Garden";
else if(gardenType.toUpperCase().equals("AG"))
gardenName="Annual garden";
else if(gardenType.toUpperCase().equals("FG"))
gardenName="Flower Garden";
else
gardenName="Illegal Garden";
}

public String getGardenName(){
return gardenName;

}

public Garden getGarden(){
if(gardenType.toUpperCase().equals("VG"))
return new VegiGarden();
else if(gardenType.toUpperCase().equals("AG"))
return new AnnualGarden();
else if(gardenType.toUpperCase().equals("FG"))
return new FlowerGarden();
else
return null;
}

}

We have last implementation class that starts making the gardens.

public class GardenMakerFactory {

public static void main(String[] args) {
GardenFactory flowerfactory=new GardenFactory("FG");
Garden fgarden= flowerfactory.getGarden();
System.out.println("Garden name is "+flowerfactory.getGardenName());
System.out.println("Specifications : ");
System.out.println("Border Plants : "+fgarden.getBorder().getPlantName());
System.out.println("Center Plants : "+fgarden.getCenter().getPlantName());
System.out.println("Shades Plants : "+fgarden.getShade().getPlantName());

GardenFactory vegitablefactory=new GardenFactory("VG");
Garden vgarden= vegitablefactory.getGarden();
System.out.println("Garden name is "+vegitablefactory.getGardenName());
System.out.println("Specifications : ");
System.out.println("Border Plants : "+vgarden.getBorder().getPlantName());
System.out.println("Center Plants : "+vgarden.getCenter().getPlantName());
System.out.println("Shades Plants : "+vgarden.getShade().getPlantName());

GardenFactory annualfactory=new GardenFactory("AG");
Garden agarden= annualfactory.getGarden();
System.out.println("Garden name is "+annualfactory.getGardenName());
System.out.println("Specifications : ");
System.out.println("Border Plants : "+agarden.getBorder().getPlantName());
System.out.println("Center Plants : "+agarden.getCenter().getPlantName());
System.out.println("Shades Plants : "+agarden.getShade().getPlantName());
}
}

Here FG cope is for Flower Garden , VG for Vegetable Garden and AG for Annual Garden
When we provides one of these codes, GardenFactory returns specific garden Object and the we can perform action of specified garden. Abstract factory pattern is typically used for giving implementation to specification (eg. jdbc servlet specifications etc...).

Factory Pattern [Creational Patterns]

Creational Patterns

All the creational patterns define the best possible way in which an object can be instantiated. These describes the best way to CREATE object instances. Now everyone knows the object instance in Java can be created using a new operator.

Book book = new Book ();

So, what’s the great stuff? Well, that’s true. The new Operator creates the instance of an object, but this is hard-coding. As I have said earlier, creating good software is difficult and so, hard coding is the last thing one should do. Also, at times the very nature of the object which is created can change according to the nature of the program. In such scenarios, we can make use of patterns to give this a more general and flexible approach.

There are five types of Creational Patterns.
1. Factory Pattern

2. Abstract Factory Pattern

3. Builder Pattern

4. Prototype Pattern

5. Singleton Pattern


I'll be explaining each in detail.


So lets start with Factory Pattern

Factory Pattern :

Factory of what? Of classes. In simple words, 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.

Let’s take an example to understand this pattern.

Example: Let’s suppose an application asks for entering the name and sex of a person. If the sex is Male (M), it displays welcome message saying Hello Mr. and if the sex is Female (F), it displays message saying Hello Ms .

The skeleton of the code can be given here.

public class Person {

private String name;
private String gender;

public String getGender() {
return gender;
}

public void setGender(String gender) {
this.gender = gender;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}


where as Male and female classes should be like the below

public class Male extends Person{

public Male(String name) {
setName("Mr. "+name);
setGender("Male");
}
}


public class Female extends Person {

public Female(String name) {
setGender("Female");
setName("Ms. "+name);
}
}


and its factory class should be like below :

public class SalutationFactory {

public static void main(String args[]) {
SalutationFactory factory = new SalutationFactory();
//System.out.println("Hello "+factory.getPerson("gaurav", "M").getName());
// OR
Person person=factory.getPerson("Gaurav", "M");
System.out.println("Hello "+person.getName());
}

public Person getPerson(String name, String gender) {
if (gender.equals("M")) {
return new Male(name);
} else if (gender.equals("F")) {
return new Female(name);
} else {
return null;
}
}
}


When to use a Factory Pattern?
The Factory patterns can be used in following cases:
1. 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.

Design Patterns

Hello Friends,
I am posting this article on patterns because I have found in many books that reading about a pattern also, does not at times gives us complete feel of how and where to use it. I want that I should be able to write something which presents the patterns in as simple a way as possible. If the reader understands about the patterns after reading this, I will consider myself successful. when i was going through a website i hav got this example but example was not efficiently written but the theme was really good and easy to understand. Here i have modified example more understandable
In this series lets start from definition of Patterns

“Pattern” as the name suggests, means series of events occurring in a definite order. we find that there is a particular way of tackling a problem. This way is easy and has been used many times successfully by a number of people earlier also. This method becomes a pattern.

So we can say "Design patterns are recurring solutions to design problems.”

Patterns: According to commonly known practices, there are 23 design patterns in Java. These patterns are grouped under three heads:
1. Creational Patterns
2. Structural Patterns
3. Behavioral Patterns

In My further posts, you will find all the patterns one by one. So keep on studying and please post your comments or questions/suggestions for making this blog successful