Tuesday, May 12, 2009
Abstract Factory [Creational Pattern]
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]
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.
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
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
Saturday, September 13, 2008
The Java Virtual Machine (JVM)
Figure - JVM emulation run on a physical CPU
The Java Virtual Machine is responsible for interpreting Java bytecode, and translating this into actions or operating system calls. For example, a request to establish a socket connection to a remote machine will involve an operating system call. Different operating systems handle sockets in different ways -but the programmer doesn't need to worry about such details. It is the responsibility of the JVM to handle these translations, so that the operating system and CPU architecture on which Java software is running is completely irrelevant to the developer.The Java Virtual Machine forms part of a large system, the Java Runtime Environment (JRE). Each operating system and CPU architecture requires a different JRE. The JRE comprises a set of base classes, which are an implementation of the base Java API, as well as a JVM. The portability of Java comes from implementations on a variety of CPUs and architectures. Without an available JRE for a given environment, it is impossible to run Java software.
Now lets have a look at JVM architecture
- A virtual machine (VM) is an abstract computer architecture
- It is Software on top of a real hardware
- Can run the same application on different machines where the VM is available
- An abstract computing machine that executes bytecode programs4.1 An instruction set and the meaning of those instructions – the bytecodes4.2 A binary format – the class file format4.3 An algorithm to verify the class file
Interpreter :The Java runtime interpreter (java) is the component of the Java Developer's Kit used to runexecutable Java bytecode classes.Just-in-time compilation :In the Java programming language and environment, a just-in-time (JIT) compiler isa program that turns Java bytecode (a program that contains instructions that must be interpreted) into instructions that can be sent directly to the processor. After you've written a Java program, the source language statements are compiled by the Java compiler into bytecode rather than into code that contains instructions that match a particular hardware platform's processor (for example, an Intel Pentium microprocessor or an IBM System/390 processor).
The bytecode is platform-independent code that can be sent to any platform and run on that platform. The Java on any platform will interpret the compiled bytecode into instructionsunderstandable by the particular processor. However, the virtual machine handles one bytecode instruction at a time. Using the Java just-in-time compiler (really a second compiler) at the particular system platform compiles the bytecode into the particular system code (as though the program had been compiled initially on that platform). Once the code has been (re-)compiled by the JIT compiler, it will usually run more quickly in the computer.The just-in-time compiler comes with the virtual machine and is used optionally. It compiles the bytecode into platform-specific executable code that is immediately executed. Sun Microsystems suggests that it's usually faster to select the JIT compiler option, especially if the method executable is repeatedly reused.
Fig : JVM DiagramJVM Architecture :