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.

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.

Functions Vs Stored Procedures



It is one of the famous or frequently asked interview question, so I am stating the difference between these two which I think is appropriate, Please correct me if I have left anything unattended here.
  1. Basic difference is a procedure can return nth values whereas function can return only one value which is mandatory to be.
  2. Function can have only input parameters whereas procedures can have both input/output parameters.
  3. Function doesn't allow an update, delete, create(DML Statements) statements into it where as Procedure do.
  4. Functions can be called from DML or select statements whereas procedures canonly call from procedure or direct through call statements.
  5. We can not do transaction management in function since it doesn't have DML queries and it is prohibited too where as procedure can be used to do transaction management.
  6. No Exception handling in Function whereas reciprocate to it Procedures do, means in procedure try catch block can be used to handle exception.
  7. Procedures can not be use in a select statement whereas function can be call in a select statement.
  8. UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section where as Stored procedures cannot be.
  9. UDFs that return tables can be treated as another rowset. This can be used in JOINs with other tables.
  10. Inline UDF's can be though of as views that take parameters and can be used in JOINs and other Rowset operations.
 Please feel free to contact me for any issues via comments.

Nth PL/SQL to get Second largest Salary from table



Today, I get an interview in which PL/SQL question was asked, we have a table lets say employee_master which has salary of employee, so requirement is to fetch the employee details who has second largest salary in table, This requirement can be implimented in various ways, Please find below the SQLs to achieve this:

  1. select top 1 Salary_amount
    from (select top 2 Salary_amount from employee_master order by salary_amount desc) a
    order by salary_amount asc
  2. ;with CTE AS(
    select row_number() over(order by salary_amount Desc) as id, salary_amount
    from employee_master
    )
    select * from CTE where id = 2 
  3. DECLARE @SQL VARCHAR(2000), @N INT --@N is level at which you  --required Salary                                         SET @N = 3
    SET @N = @N - 1
     SET @sql = 'select top 1 salary_amount from employee_master where salary not in ( SELECT TOP ' + CAST(@n AS VARCHAR(100))  + ' salary FROM ABC  )'
EXEC (@SQL)
  1. SELECT MAX(SALARY) FROM EMPLOYEE WHERE SALARY NOT IN (SELECT MAX(SALARY) FROM EMPLOYEE)
Please do let me know in case of any addition, looking forward to see your comments for ad-ons.

Friday 29 June 2012

Types of IOC(Inversion of Control) or DI(Dependency Injection)

There are two types of dependency injection: setter injection and constructor injection.

Setter Injection: Normally in all the java beans, we will use setter and getter method to set and get the value of property as follows:

public class namebean {
String name;    
public void setName(String a) {
             name = a;
}    
public String getName() {    
return name;
}
}

We will create an instance of the bean 'namebean' (say bean1) and set property as bean1.setName("tom"); Here in setter injection, we will set the property 'name' in spring configuration file as showm below:
<bean id="bean1" class="namebean">
<property name="name" > <value>tom</value> </property>
</bean>

The subelement <value> sets the 'name' property by calling the set method as setName("tom"); This process is called setter injection. To set properties that reference other beans <ref>, subelement of <property> is used as shown below,
<bean id="bean1" class="bean1impl">
<property name="game">
<ref bean="bean2"/>
</property>
</bean>
<bean id="bean2" class="bean2impl" />

Constructor injection: For constructor injection, we use constructor with parameters as shown below,

public class namebean {
String name;
public namebean(String a) {
name = a;
}
 }

We will set the property 'name' while creating an instance of the bean 'namebean' as namebean bean1 = new namebean("tom");

Here we use the <constructor-arg> element to set the the property by constructor injection as
<bean id="bean1" class="namebean">           <constructor-arg><value>My Bean Value</value></constructor-arg></bean>


IOC(Inversion of control) Vs DI(Dependency injection)

IOC and DI are one of the same thing in aspects of Spring Framework, Both are meant to be for same functionality.

Dependency injection (DI) is a programming design pattern and architectural model, sometimes also referred to as inversion of control or IOC, although technically speaking, dependency injection specifically refers to an implementation of a particular form of IOC. 

Dependency Injection describes the situation where one object uses a second object to provide a particular capacity. For example, being passed a database connection as an argument to the constructor instead of creating one internally. The term "Dependency injection" is a misnomer, since it is not a dependency that is injected, rather it is a provider of some capability or resource that is injected. 

There are three common forms of dependency injection: 
1.) Setter
2.) Constructor
3.) Interface-based injection. 

Dependency injection is a way to achieve loose coupling. Inversion of control (IOC) relates to the way in which an object obtains references to its dependencies. This is often done by a lookup method. The advantage of inversion of control is that it decouples objects from specific lookup mechanisms and implementations of the objects it depends on. As a result, more flexibility is obtained for production applications as well as for testing.

What is Inversion Of Control(IOC)?

Inversion of control or dependency injection (which is a specific type of IoC) is a term used to resolve object
dependencies by injecting an instantiated object to satisfy dependency as opposed to explicitly requesting an
object. So objects will not be explicitly requested but objects are provided as needed with the help of an Inversion Of Controller container (e.g. Spring etc).

This is analogous to the Hollywood principal where the servicing objects say to the requesting client code (i.e. the caller) “don’t call us, we’ll call you”. Hence it is called inversion of control.


Many of us are familiar with the software development context where client code collaborates with other dependent objects (or servicing objects) by knowing which objects to talk to, where to locate them and how to talk with them. This is achieved by embedding the code required for locating and instantiating the requested components within the client code.

Simple Code(Without IOC)


class TestSO {
  public void getSO(String Prop) {
      SoDAO dao = new  SoDAOImpl();
      List listSo = dao.find SoByProp(Prop);
     }
}



called code:
interface SoDAO (){
     public abstract List findSoByProp(Prop);
}

interface SoDAOImpl extends SoDAO (){
   public List findSoByProp(Prop) {
  }
}

This tight coupling can be resolved by applying the factory design pattern and program to interfaces not to
implementations driven development. Simplified factory class implemented with a singleton design pattern:

class SoDAOFactory {
 private static final SoDAOFactory singleton = new SoDAOFactory();
 private SoDAOFactory(){}
 public SoDAOFactory getInstance(){
 return singleton;
}

public SoDAO getDAO(){
   return new SoDAOImpl();
  }
}

Now the caller code should be changed to:

class SoTest {
 public void getSo(String Prop) {
 SoDAO dao = SoDAOFactory.getInstance().getDAO();
 List listSo = dao.findSoByProp(Prop);
}
}

But the factory design pattern is still an intrusive mechanism because servicing objects need to be requested
explicitly. Also if you work with large software systems, as the system grows the number of factory classes can become quite large. All the factory classes are simple singleton classes that make use of static methods and field variables, and therefore cannot make use of inheritance. This results in same basic code structure repeated in all the factory classes.


Let us look at how dependency injection comes to our rescue. It takes the approach that clients declare their
dependency on servicing objects through a configuration file (like spring-config.xml) and some external piece of code (e.g. Spring) assumes the responsibility of locating and instantiating these servicing components and
supplying the relevant references when needed to the client code whereby acting as the factory objects. This
external piece of code is often referred to as IoC (specifically known as dependency injection) container or
framework.

Look at SpringConfig.xml file below:

<beans>
<bean id="SoBean" class="SoTest" singleton="false" >
<constructor-arg>
<ref bean="SoDao" />
</constructor-arg>
</bean>
<bean id="SoDao” class="SoDAOImpl" singleton="false" />
</beans>

Now code will changes to below:

class SoTest {
   private SoDAO dao = null;
   public SoBO(SoDAO dao) {
     this.dao = dao;
    }
    public void getSo(String prop) {
       List listSo = dao.findSoByProp(prop);
    }
 }

Your calling code would be (e.g. from a Web client or EJB client):

    ApplicationContext ctx = new FileSystemXmlApplicationContext("SpringConfig.xml");
    SoTest  sOo = (SoTest)ctx.getBean("SoBean");
    String prop = "beneton";
    sOo.getSo(prop)

You can use IoC containers like Spring framework to inject your business objects and DAOs into your calling
classes. Dependencies can be wired by either using annotations or using XML as shown above. Tapestry 4.0
makes use of the Hivemind IoC container for injecting application state objects, pages etc.
IoC or dependency injection containers generally control creation of objects (by calling “new”) and resolve
dependencies between objects it manages. Spring framework, Pico containers, Hivemind etc are IoC containers to name a few. IoC containers support eager instantiation, which is quite useful if you want self-starting services that “come up” on their own when the server starts. They also support lazy loading, which is useful when you have many services which may only be sparsely used.

Site Search