Wednesday, November 3, 2010

Design Patterns in Java

 Creational Pattern 
Question : What is singleton Pattern in java?
Answer 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”.


What is Abstract Factory Pattern?
Ans : 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.

Creational Patterns - Builder Pattern
Builder, as the name suggests builds complex objects from simple ones 
step-by-step. It separates the construction of complex objects from their representation.
Question : Define design Patterns ?
Answer : Design patterns are recurring solutions to designing problems.
Question : How many Design-patterns and sub classes?
Answer : 23 design patterns under 3 sub classes.
            1) Creational Patterns.
            2)Behavioral Patterns.
            3)Structural Patterns.
Question : What is abstract factory pattern ?
Answer: it is one among the Creational pattern.returns the factory of classes.
Advantage : It isolates the names of concrete classes. the names of the actual implementing
classes not needed to be known on client side.because of this we can change the imple-
mentation from one factory to another.


Explain in layman Words:
Suppose i have to get the specification of one of the 3 computers (server,PC,Mainframe)
 the client really need not to know the name of that class(here suppose say Mainframe).
he can simply pass the name of the computer to a computer which will return exact
specification of that computer.
Example : 
public class ComputerType {
 private Computer comp;public static void main(String[] args) {
  ComputerType type = new ComputerType();Computer computer = type.getComputer("Server");
System.out.println("Monitor: "+computer.getMonitor().getSpecification());
System.out.println("RAM: "+computer.getRAM().getSpecification());
System.out.println("Processor: "+computer.getProcessor().getSpecification());
 }  
  /**
* Returns a computer for a type
*
* @param computerType String, PC / Workstation / Server
* @return Computer
*/
 public Computer getComputer(String computerType) {
  if (computerType.equals("PC"))
comp = new PC();
else if(computerType.equals("Workstation"))
comp = new Workstation();
else if(computerType.equals("Server"))
comp = new Server();
return comp;
 } 
}// End of class

Here where the user does not really need to the names of the server class.

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...