History Monuments Details

Read every monuments of country in detail, Check out how they created, about the history and hidden things against each monuments.

Latest News about the world

Be active and pro to have latest news, here you can find latest news with out breaks.

Get the latest events happening in world

Avail the service to be updated about the unseen/unavailable events happening in the world.

Lets hit the new Technologies

Be Pro by Learning new technologies free with latest blogs written by us at techytreat.blogspot.in

Learn new things about the country

Here you can learn new and unique things about country.

Friday, 29 June 2012

What is Abstract Factory Design Patterns?

Using references to interfaces instead of references to concrete classes is an important way of minimizing ripple effects. The user of an interface reference is always protected from changes to the underlying implementation.
The Abstract Factory pattern is one example of this technique. Users of an Abstract Factory can create families of related objects without any knowledge of their concrete classes. (A typical business application would usually not need to use this technique - it is more suitable for toolkits or libraries.)

Example
An Abstract Factory is a major part of the full Data Access Object scheme. Here, the idea is to allow the business layer to interact with the data layer almost entirely through interface references. The business layer remains ignorant of the concrete classes which implement the datastore.
There are two distinct families of items here :
  • the various datastore implementations (MySql, FileScheme)
  • the various business objects which need persistence (UserDevice, etc.)
This corresponds to the two operations which must be done to return a persisted object. The type of datastore is first determined (an implementation of DAOFactory is returned), using a Factory Method.
(This example would be much improved by not having imports of ServletConfig all over the place.) 
package myapp.data;

import javax.servlet.ServletConfig;

/**
* Allows selection of a DAOFactory, without the user being
* aware of what choices are available.
*
* This style allows the data layer to make the decision regarding what
* DAOFactory is to be used by the business layer.
*/
public final class DatastoreSelector {

  /**
  * @param aConfig is non-null.
  */
  public static DAOFactory getDAOFactory( ServletConfig aConfig ){
    //demonstrate two implementation styles :
    return stringMappingImpl( aConfig );
    //return classNameImpl( aConfig );
  }

  // PRIVATE //

  /**
  * Use an ad hoc String mapping scheme, and introduce an if-else
  * branch for each alternative.
  */
  private static DAOFactory stringMappingImpl( ServletConfig aConfig ){
    if ( aConfig == null ) {
      throw new IllegalArgumentException("ServletConfig must not be null.");
    }
    //examine the config to extract the db identifier
    final String storageMechanism = aConfig.getInitParameter("DatastoreName");
    if ( storageMechanism.equals("MySql")) {
      return new DAOFactoryMySql( aConfig );
    }
    else if ( storageMechanism.equals("FileScheme") ) {
      return new DAOFactoryFileScheme( aConfig );
    }
    else {
      throw new IllegalArgumentException("Unknown datastore identifier.");
    }
  }

  /**
  * Make direct use of the class name, and use reflection to create the
  * object.
  */
  private static DAOFactory classNameImpl( ServletConfig aConfig ){
    DAOFactory result = null;
    //examine the config to extract the class name
    final String storageClassName = aConfig.getInitParameter("DatastoreClassName");
    try {
      Class storageClass = Class.forName(storageClassName);
      //Class.newInstance can be used only if there is a no-arg constructor ;
      //otherwise, use Class.getConstructor and Constructor.newInstance.
      Class[] types = { javax.servlet.ServletConfig.class };
      java.lang.reflect.Constructor constructor = storageClass.getConstructor(types);
      Object[] params = { aConfig };
      result = (DAOFactory) constructor.newInstance( params );
    }
    catch (Exception ex){
      System.err.println("Cannot create DAOFactory using name: " + storageClassName);
      ex.printStackTrace();
    }
    return result;
  }
} 

package myapp.data;

/**
* Returns an implementation of all XXXDAO interfaces.
*/
public interface DAOFactory {

  /**
  * Returns an implementation of DeviceDAO, specific to a
  * particular datastore.
  */
  DeviceDAO getDeviceDAO() throws DataAccessException;

  /**
  * Returns an implementation of UserDAO, specific to a
  * particular datastore.
  */
  UserDAO getUserDAO() throws DataAccessException;
} 


Then, each DAOFactory implementation can return its implementations of the XXXDAO interfaces (DeviceDAOUserDAO), which are the concrete worker classes which implement persistence. 
package myapp.data;

import javax.servlet.ServletConfig;

/**
* Package-private implementation of DAOFactory.
* This is for a MySql database.
*/
final class DAOFactoryMySql implements DAOFactory {

  DAOFactoryMySql( ServletConfig aServletConfig ){
    if ( aServletConfig == null ) {
      throw new IllegalArgumentException("ServletConfig must not be null.");
    }
    fConfig = aServletConfig;
  }

  public UserDAO getUserDAO() throws DataAccessException {
    return new UserDAOMySql(fConfig);
  }

  public DeviceDAO getDeviceDAO() throws DataAccessException {
    return new DeviceDAOMySql(fConfig);
  }

  /// PRIVATE ////
  private final ServletConfig fConfig;
} 

package myapp.data;

import javax.servlet.ServletConfig;

/**
* Package-private implementation of DAOFactory.
* This is for an ad hoc file scheme.
*/
final class DAOFactoryFileScheme implements DAOFactory {

  DAOFactoryFileScheme( ServletConfig aServletConfig ){
    if ( aServletConfig == null ) {
      throw new IllegalArgumentException("ServletConfig must not be null.");
    }
    fConfig = aServletConfig;
  }

  public UserDAO getUserDAO() throws DataAccessException {
    return new UserDAOFileScheme(fConfig);
  }

  public DeviceDAO getDeviceDAO() throws DataAccessException {
    return new DeviceDAOFileScheme(fConfig);
  }

  /// PRIVATE ////
  private final ServletConfig fConfig;
} 


Here is an example of a XXXDAO interface, and a toy implementation for a MySql database. 
package myapp.data;

import myapp.business.Device;

/**
* The business layer talks to the data layer about storage of Device objects
* through a DeviceDAO reference.
*
* DataAccessException is a wrapper class, which exists only to wrap
* low-level exceptions specific to each storage mechanism (for example,
* SQLException and IOException). When an implementation class throws
* an exception, it is caught, wrapped in a DataAccessException, and then
* rethrown. This protects the business layer from ripple effects caused by
* changes to the datastore implementation.
*/
public interface DeviceDAO {
  Device fetch( String aId ) throws DataAccessException;
  void add( Device aDevice ) throws DataAccessException;
  void change( Device aDevice ) throws DataAccessException;
  void delete( Device aDevice ) throws DataAccessException;
}
 

package myapp.data;

import myapp.business.Device;
import java.net.InetAddress;
import javax.servlet.ServletConfig;

/**
* An implementation of DeviceDAO which is specific to a MySql database.
*
* This class must be package-private, to ensure that the business layer
* remains unaware of its existence.
*
* Any or all of these methods can be declared as synchronized. It all depends
* on the details of your implementation.
*
* Note that it is often possible to use properties files (or ResourceBundles) to
* keep SQL out of compiled code, which is often advantageous.
*/
final class DeviceDAOMySql implements DeviceDAO {

  DeviceDAOMySql( ServletConfig aConfig ) {
    //..elided
  }

  public Device fetch( String aId ) throws DataAccessException {
    //create a SELECT using aId, fetch a ResultSet, and parse it into a Device
    return null; //toy implementation
  }

  synchronized public void  add( Device aDevice ) throws DataAccessException{
    //parse aDevice into its elements, create an INSERT statement
  }

  synchronized public void change( Device aDevice )  throws DataAccessException{
    //parse aDevice into its elements, create an UPDATE statement
  }

  synchronized public void delete( Device aDevice )  throws DataAccessException {
    //extract the Id from aDevice, create a DELETE statement
  }
} 


It is important to note most of the data layer's concrete classes are package-private - only DatastoreSelector and DataAccessException are public. 

Friday, 4 May 2012

Types of Java Design Patterns?

We have no of issues so having common solutions We have 200+ Types of Java Design Patterns, but to get it caegorise we have trim some of the design patter according to most common or frequent issues and below are some of them:

Creational Patterns
  1. Abstract Factory
  2. Builder
  3. Factory Method
  4. Prototype
  5. Singleton

Structural Patterns 
  1. Adapter
  2. Bridge
  3. Composite
  4. Decorator
  5. Façade
  6. Flyweight
  7. Proxy

Behavioral Patterns
  1. Chain of Responsibility
  2. Command
  3. Interpreter
  4. Iterator
  5. Mediator
  6. Memento
  7. Observer
  8. State
  9. Strategy
  10. Template Method
  11.  Visitor

J2EE Patterns
  1. MVC
  2. Business Delegate
  3. Composite Entity
  4. Data Access Object
  5. Front Controller
  6. Intercepting Filter
  7. Service Locator
  8. Transfer Object
Thanks for reading, Please do comment so as to get best for you.

Interview Questions on Design pattern

Till now I have given number of interview and below are the questions asked most of the time:

  1. What is Singleton Pattern, Where to use Singleton Pattern?
  2. What is Creational Patterns?
  3. What is Factory Design Patterns?
  4. What is Abstract Factory Patterns?
  5. What is Prototype Desingn Patterns?
  6. What is Fasad Design Patters?
  7. Why we use Design Patterns, and where not to use Design Pattern?
  8. What are Anti Patterns, What is the used and where to use Anti Design Patterns?
These are the few questions asked in my interview, and I am searching for best answer for these.

What is Singleton Design Pattern?

Singleton Pattern is one of the well known and ask most of the times in interview questions in design patterns, if I am not wrong then 90  percent of the cases singleton pattern is asked, but I don't understand why this is so famous may be due to its criticality and  frequently occur problem in software coding, WHY, WHY WHY...

Is any one has the answer, Think about Performance!!!.

Performance is one of the target for any application and singleton pattern plays a vital role in improving performance, Imagine the application with lots of objects created and none of the object is destroyed by their own and there is  mechanism to destroy of these objects, Now I don't think anyone will agree for such design or application. Yes here is Singleton pattern come in picture. Create a single instance of a class and use it through out the application.

One scenario I am missing here what will happen, when no of component of application uses single instance of a class, Doesn't this hamper the application performance. Do we need to create every class as singleton.

I think No No No. So question is Where to use Singleton pattern?

Singleton pattern is generally used to service instance independent or static data where multiple threads can access data at same time. example can be logging class.

Singletons often control access to resources such as database connections or sockets. For example, if you have a license for only one connection for your database or your JDBC driver has trouble with multithreading, the Singleton makes sure that only one connection is made or that only one thread can access the connection at a time. If you add database connections or use a JDBC driver that allows multithreading, the Singleton can be easily adjusted to allow more connections.


How to follow or implement Singleton Design Pattern?

Follow the below suedo to implement singleton pattern in class:
  1. Create a private static variable of a class
  2. Create private construtor so that constructor can be called from outside.
  3. Create a public method which will return the instance of class created at step 1.

public class MySingleton { 
 private static MySingleton _instance; 

 private MySingleton() { 
 } 

 public static synchronized MySingleton getInstance() { 
  if (_instance==null) { 
   _instance = new MySingleton(); 
  } 
  return _instance; 
 } 

Thanks for the reading please do comment to facilitate you better.

Wednesday, 2 May 2012

Are Design Patterns really needed.

Before we start explaining the design patterns, first we should now some basic things related to Design Patterns:
  1. What is Design Pattern?
  2. Why Design Patterns?
What is Design Pattern?
design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. Lets say we have a problem which we used to face very frequently then we used to have a common solution to it, and design patterns are the solutions of frequently occurring problems in software coding or   cycle.   

Why Design Patterns?
- Save Time to provide the solution, since we already now the solution.
- Standard way to provide solution to software.

Types of Design Patterns:
  1. Creational
  2. Structural
  3. Behavioral
Creational patterns are ones that create objects for you, rather than having you instantiate objects directly. This gives your program more flexibility in deciding which objects need to be created for a given case. Structural patterns help you compose groups of objects into larger structures, such as complex user interfaces or accounting data. Behavioral patterns help you define the communication between objects in your system and how the flow is controlled in a complex program.

Thanks for reading...I will keep posting....

Site Search