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.

Showing posts with label Java Design Patterns. Show all posts
Showing posts with label Java Design Patterns. Show all posts

Tuesday, 3 July 2012

Flyweight Design Pattern


Some programs require to have a large number of objects that have some shared state among them. Consider for example a game of war, were there is a large number of soldier objects; a soldier object maintain the graphical representation of a soldier, soldier behavior such as motion, and firing weapons, in addition soldier’s health and location on the war terrain. Creating a large number of soldier objects is a necessity however it would incur a huge memory cost. Note that although the representation and behavior of a soldier is the same their health and location can vary greatly.



Why Fly Weight?

The intent of this pattern is to use sharing to support a large number of objects that have part of their internal state in common where the other part of state can vary.

Where to use "Flyweight Design Pattern"?
Following reasons to choose flyweight design pattern,
  • When we need to create large number of objects.
  • Memory Constraints due to large number ob object creation.
  • When most of the object attributes can be made external and shared.
  • The application must not mandate unique objects, as after implementation same object will be used repeatedly.
  • Its better when extrinsic state can be computed rather than stored.
Fly Weight is about sharing memory of object where needed. If we have a class star and we need to create an application for universe so if we create the object for each star in universe then think about the application performance so what a fly weight pattern can do here and how to implement the Design pattern.

The object which we are going to create in high number should be analyzed before going for flyweight. Idea is to create lesser number of objects by reusing the same objects. Create smaller groups of objects and they should be reused by sharing. Closely look at objects properties and they can be segregated as two types intrinsic and extrinsic. Sharing is judged with respect to a context. Lets take the example of editors.

Consider a simple text editor where we can use only alphabet set A to Z. If we are going to create 100 page document using this editor we may have 200000 (2000 X 100) characters (assuming 2000 characters / page). Without flyweight we will create 200000 objects to have fine grained control. With such fine control, every character can have its own characteristics like color, font, size, etc. How do we apply flyweight here?

Flyweight Implementation

The object with intrinsic state is called flyweight object. When we implement flyweight we create concrete objects and have the intrinsic state stored in that. To create those concrete objects we will have factory and that is called Flyweight factory. This factory is to ensure that the objects are shared and we don’t end up creating duplicate objects.

Let us take an example scenario of drawing. We need to draw different geometrical shapes like rectangles and ovals in huge number. Every shape may vary in colour, size, fill type, font used. For implementation sake lets limit our shapes to two rectangle and oval. Every shape will be accompanied by a label which directly maps it with the shape. That is all rectangles will have label as ‘R’ and all ovals will have label as ‘O’.

Now our flyweight will have intrinsic state as label only. Therefore we will have only two flyweight objects. The varying properties colour, size, fill type and font will be extrinsic. We will have a flyweight factory that will maintain the two flyweight objects and distribute to client accordingly. There will be an interface for the flyweights to implement so that we will have a common blueprint and that is the flyweight interface.

Client code will use random number generators to create extrinsic properties. We are not storing the extrinsic properties anywhere, we will calculate on the fly and pass it. Use of random number generator is for convenience.

// Flyweight object interface
public interface CoffeeOrder {
    public void serveCoffee(CoffeeOrderContext context);
}

// ConcreteFlyweight object that creates ConcreteFlyweight
public class CoffeeFlavor implements CoffeeOrder {
    private String flavor;

    public CoffeeFlavor(String newFlavor) {
        this.flavor = newFlavor;
    }

    public String getFlavor() {
        return this.flavor;
    }

    public void serveCoffee(CoffeeOrderContext context) {
        System.out.println("Serving Coffee flavor " + flavor + " to table number " + context.getTable());
    }
}

public class CoffeeOrderContext {
   private int tableNumber;

   public CoffeeOrderContext(int tableNumber) {
       this.tableNumber = tableNumber;
   }

   public int getTable() {
       return this.tableNumber;
   }
}

import java.util.HashMap;
import java.util.Map;

//FlyweightFactory object
public class CoffeeFlavorFactory {
    private Map<String, CoffeeFlavor> flavors = new HashMap<String, CoffeeFlavor>();

    public CoffeeFlavor getCoffeeFlavor(String flavorName) {
        CoffeeFlavor flavor = flavors.get(flavorName);
        if (flavor == null) {
            flavor = new CoffeeFlavor(flavorName);
            flavors.put(flavorName, flavor);
        }
        return flavor;
    }

    public int getTotalCoffeeFlavorsMade() {
        return flavors.size();
    }
}

public class TestFlyweight {
   /** The flavors ordered. */
   private static CoffeeFlavor[] flavors = new CoffeeFlavor[100];
   /** The tables for the orders. */
   private static CoffeeOrderContext[] tables = new CoffeeOrderContext[100];
   private static int ordersMade = 0;
   private static CoffeeFlavorFactory flavorFactory;

   public static void takeOrders(String flavorIn, int table) {
       flavors[ordersMade] = flavorFactory.getCoffeeFlavor(flavorIn);
       tables[ordersMade++] = new CoffeeOrderContext(table);
   }

   public static void main(String[] args) {
       flavorFactory = new CoffeeFlavorFactory();

       takeOrders("Cappuccino", 2);
       takeOrders("Frappe", 1);
       takeOrders("Frappe", 1);
       takeOrders("Xpresso", 1);
       takeOrders("Frappe", 897);
       takeOrders("Cappuccino", 97);
       takeOrders("Cappuccino", 97);
       takeOrders("Frappe", 3);
       takeOrders("Xpresso", 3);
       takeOrders("Cappuccino", 3);
       takeOrders("Xpresso", 96);
       takeOrders("Frappe", 552);
       takeOrders("Cappuccino", 121);
       takeOrders("Xpresso", 121);

       for (int i = 0; i < ordersMade; ++i) {
           flavors[i].serveCoffee(tables[i]);
       }
       System.out.println(" ");
       System.out.println("Count of CoffeeFlavor objects made: " +      
       flavorFactory.getTotalCoffeeFlavorsMade());
   }
}

What is Factory Design Patterns?


Creational Patterns
     -Factory Pattern

Factory of classes. In simple words, if we have a super class and nth 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.

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. <Name> and if the sex is Female (F), it displays message  Welcome to application,  Ms <Name>.

The skeleton of the code can be given here.

public class Person {
// name stringpublic String name;// gender : M or Fprivate 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(" Welcome to application, Mr. "+fullName);}
}// End of class

Also, the class Female

public class Female extends Person {
public Female(String fullNname) {System.out.println("Welcome to application, 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);elsereturn 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 Bhanu and M:
java Bhanu M
The result returned is: “Hello Mr. Bhanu”.

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.

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.

Site Search