Wednesday, November 3, 2010

Design Patterns in Java

 Creational Pattern 
What is singleton Pattern in java?
Ans The Singleton pattern, for example, is used to encapsulate the creation
of an object in order to maintain control over it. This not only ensures that 
only one is created, but also allows lazy instantiation; that is, the instantiation
of the object can be delayed until it is actually needed.
This is especially beneficial if the constructor needs to perform a costly
 operation, such as accessing a remote database.
Example of Singleton Class:



10 :public class SingletonObject
{
20 :private SingletonObject()
  {
    // no code req'd
  }
30:public static synchronized SingletonObject getSingletonObject()
  {
40:   if (ref == null)
        // it's ok, we can call this constructor
50:      ref = new SingletonObject();  
60:    return ref;
  }

70: public Object clone()
80: throws CloneNotSupportedException
  {
90:    throw new CloneNotSupportedException(); 
    // that'll teach 'em
  }

100: private static SingletonObject ref;
}

Observation : 
line 70: Creating method clone(), throw an exception, if any class trying 
to clone the singleton object.
line 30 - 60 :
Creates only one instance of the singleton class if not created early,and this
can access only one thread at a time.
line 20: Private constructor. so that so that other classes can't create a new instance.


What is Factory Pattern in Creational Pattern ?
DefinitionFactory 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.


When to 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 of Factory 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 {
 // name string
public String name;
// gender : M or F
private String gender;
public String getName() {
return name;
}

public String getGender() {
return gender;
}
}// End of class

This is a simple class Person having methods for name and gender. Now, 
we will have two sub-classes, Male and Female which will print the welcome
message on the screen.
public class Male extends Person {
 public Male(String fullName) {
System.out.println("Hello Mr. "+fullName);
}
}// End of class

Also, the class Female
public class Female extends Person {
 public Female(String fullNname) {
System.out.println("Hello Ms. "+fullNname);
}
}// End of class
Now, we have to create a client, or a SalutationFactory which will return
the welcome message depending on the data provided.
public class SalutationFactory {
 public static void main(String args[]) {
SalutationFactory factory = new SalutationFactory();
factory.getPerson(args[0], args[1]);
}
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;
}
}// End of class
This class accepts two arguments from the system at runtime and prints the 
names.
Running the program:
After compiling and running the code on my computer with the arguments 
Prashant and M:


javac> java Prashant M
The result returned is: “Hello Mr. Prashant”.



No comments:

AWS certification question

AWS AWS Hi! this is for questions related to AWS questions. EC2 instances EC2 storage types cold HDD : 1. Defines performance in terms...