> My Java Aquarium ***

Tuesday, October 21, 2008

My understanding of Factory Pattern

Going by definition Factory pattern is a creational design pattern used in software development to encapsulate the processes involved in the creation of objects.

In simple terms we can say that factory pattern is a good choice when we need to create object depending on some parameter at runtime.

Let’s say if we have a super class and sub-classes, and based on data provided (any parameter), we have to return the object of one of the sub-classes, then factory pattern is the ideal choice.

Lets take a simple example to understand its working..

Suppose we have an application which stores Customer details like name and sex etc. Depending on sex the application will create either a male or a female object and accordingly print a hello message.

public class Customer {

public String name;

//gender : M or F

private String gender;

public String getName() {

return name;

}

public String getGender() {

return gender;

}

}

Customer class is having methods for name and gender. And the sub classes will print hello message as shown below.

public class Male extends Customer {

public Male(String name) {

System.out.println("Hello Mr. "+name);

}

}

public class Female extends Customer {

public Female(String name) {

System.out.println("Hello Ms. "+name);

}

}

Now create a client, called CustomerFactory which will return Male or Female object depending on the data provided

public class CustomerFactory {

public static void main(String args[]) {

CustomerFactory factory = new CustomerFactory();

factory.getCustomer(args[0], args[1]);

}

public Customer getCustomer(String name, String gender) {

if (gender.equals("M"))

return new Male(name);

else if(gender.equals("F"))

return new Female(name);

else

return null;

}

}

On compiling and running this client program..

Java CustomerFactory Sarah F

The output is: “Hello Ms. Sarah”.

Now let’s summarize when to use Factory Pattern

· When a class does not know which class of objects it must create.

· When we want to encapsulate the process of creating the objects.

· When we have to create an object of any one of sub-classes depending on the data provided.

So now its time to create your own factories as you wish J

Labels: ,

Friday, October 10, 2008

Comparing object and sorting them in java using Comparator and Comparable interfaces

As we know sorting is one of the very common tasks especially when we have a list or collection of objects. For example if we have a list of Employees then we would like to display it in some order may be by sorting them by EmpId or name. In these situations both (Comparator and Comparable) will become handy.

About Comparators and Comparables

Simply putting java.lang.Comparator and java.lang.Comparable are used for comparing objects in java.

Comparator

A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.lang.Comparator interface.

Comparable

A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.

Now lets see how we can use these interfaces

Each of these has one method to be implemented by user.

java.lang.Comparable: int compareTo(Object obj1)
This method compares this object with obj1 object. Returned int value has the following meanings.

  1. positive – this object is greater than obj1
  2. zero – this object equals to obj1
  3. negative – this object is less than obj1


java.lang.Comparator: int compare(Object obj1, Object obj2)
This method compares obj1 and obj2 objects. Returned int value has the following meanings.

  1. positive – obj1 is greater than obj2
  2. zero – obj1 equals to obj2
  3. negative – obj1 is less than obj1

Note:

java.util.Collections.sort(List) and java.util.Arrays.sort(Object[]) methods can be used to sort using natural ordering of objects.
java.util.Collections.sort(List, Comparator) and java.util.Arrays.sort(Object[], Comparator) methods can be used if a Comparator is available for comparison.

Now let’s do a simple example to see these concepts in real scenario.

(1) First we will write a simple Employee class as below..

public class Employee {

private int empId;

private String name;

public Employee(int empId, String name) {

this.empId=empId;

this.name=name;

}

public int getEmpId() {

return empId;

}

public void setEmpId(int empId) {

this.empId = empId;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

(2) Next we will write a class to implement compare() method of comparator interface. You can see below in the code that we are comparing Employee object by name attribute. Instead of name we can use Empid attribute to compare objects for sorting. The choice depends on the need.

public class NameComparator implements Comparator{

public int compare(Object emp1, Object emp2) {

String emp1Name = ( (Employee) emp1).getName();

String emp2Name = ( (Employee) emp2).getName();

return emp1Name.compareTo(emp2Name);

}

}

(3) Finally we will write a test class to use our NameComparator class for comparing and sorting Employee objects.

import java.util.ArrayList;

import java.util.Collections;

import java.util.HashSet;

import java.util.Iterator;

import java.util.List;

import java.util.Set;

public class TestEmployeeSort {

public static void main(String args[]){

//create a set of Employee object without any specific order

Set<Employee> set = new HashSet<Employee>();

set.add(new Employee(3, "Raj"));

set.add(new Employee(1, "Sajid"));

set.add(new Employee(6, "Sowmya"));

set.add(new Employee(2, "Manu"));

set.add(new Employee(7, "Larry"));

set.add(new Employee(4, "Suresh" ));

set.add(new Employee(8, "Harry"));

set.add(new Employee(5, "Ashu"));

//converting set to list

List<Employee> list=new ArrayList<Employee>(set);

System.out.println("Order of employee before sorting is");

Iterator i=list.iterator();

while(i.hasNext())

{

Employee e1=(Employee) i.next();

System.out.println(e1.getEmpId() + "\t" + e1.getName() );

}

//calling sort method and passing the list of employees and a new instance of our NameComparator class

Collections.sort(list,new NameComparator());

System.out.println("Order of employee after sorting is");

for (Employee e: list) {

System.out.println(e.getEmpId() + "\t" + e.getName() );

}

}

}

After running this test class we would get following output.

Order of employee before sorting is

3 Raj

8 Harry

6 Sowmya

1 Sajid

4 Suresh

5 Ashu

7 Larry

2 Manu

Order of employee after sorting is

5 Ashu

8 Harry

7 Larry

2 Manu

3 Raj

1 Sajid

6 Sowmya

4 Suresh

Labels: