Friday, February 28, 2014

Comparable and Comparator Interfaces in Java

In this post, we'll see why we need Comparable and Comparator Interfaces, how to use and when to use. We'll also look into the difference between between in terms of their requirement and use.



As their name suggest, Comparable and Comparator Interfaces are used to compare similar objects for example, while performing searching and sorting.
Assume that you have a container containing a list of Person object.Now, how you compare two Person objects? There are any number of comparable attributes, such as SSN, name, driving-license number, and so on. Two objects can be compared on SSN as well as person’s name; this depends on the context. Hence, the criterion to compare the Person objects cannot be predefined; a developer has to define this criterion. Java defines Comparable and Comparator interfaces to achieve the same.

Comparable Interface
The Comparable class has only one method compareTo(), which is declared as follows:
public interface Comparable<T>
int compareTo(T o) : Compares this object with the specified object for order.

  • This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.
  • Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a Comparator.
  • The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2) for every e1 and e2 of class C. Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.
  • Virtually all Java core classes that implement Comparable have natural orderings that are consistent with equals. One exception is java.math.BigDecimal, whose natural ordering equates BigDecimal objects with equal values and different precisions (such as 4.0 and 4.00).

The Comparable interface is used by the Collections.sort() method and the java.util.Arrays.sort() method to sort Lists and arrays of objects, respectively. 
To implement Comparable, a class must implement a single method, compareTo(). Since you are implementing the compareTo() method in a class, you have this reference available. You can compare the current element with the passed Element and return an int value. What should the int value be? Well, here are the rules for returning the integer value:

return 1 if current object > passed object
return 0 if current object == passed object
return -1 if current object < passed object

When you compare integer with each other numeric order will be follow and in case of string lexicographic comparison will follow. For user-defined classes, you need to find the natural order in which you can compare the objects. For example, for a Student class, StudentId might be the natural order for comparing Student objects.

The sort() method uses compareTo() to determine how the List or object array should be sorted. Since you get to implement compareTo() for your own classes, you can use whatever weird criteria you prefer, to sort instances of your classes.

Example: In this example, we'll sort the object of Student class on the basis of ID and to sort user-defined object we need to implement Comparable interface


We have implemented the Comparable<Student> interface. When you call the sort() method, it calls the compareTo() method to compare Student objects by their IDs. Since Student IDs are unique, it is a natural comparison order that works well.
Note : It’s important to remember that when you override equals() you MUST take an argument of type Object, but that when you override compareTo() you should take an argument of the type you’re sorting.

We can sort the list, but...
There's a new problem - Suppose wants two different views of the Student list, one by song id and one by grade !
But when you make a collection element comparable (by having it implement Comparable), you get only one chance to implement the compareTo() method. So what can you do?
The horrible way would be to use a flag variable in the Song class, and then do an if test in comparator) and give a different result depending on whether the flag is set to use title or artist for the comparison.
But that's an awful and brittle solution, and there 's something much better. Something built into the API for just this purpose-when you want to Sort the same thing in more than one way.
If we see sort() method is overloaded to take something called a Comparator. Now we'll how this will help in sorting on the basis of different criteria.

Comparator interface
The Comparator interface gives you the capability to sort a given collection any number of different ways. 

  • The other handy thing about the Comparator interface is that you can use it to sort instances of any class—even classes you can't modify—unlike the Comparable interface, which forces you to change the class whose instances you want to sort. 
  • The Comparator interface is also very easy to implement, having only one method, compare(). 
public interface Comparator<T>
int compare(T o1, T o2) : Compares its two arguments for order.
boolean equals(Object obj) : Indicates whether some other object is "equal to" this comparator.

  • A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order.
    Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don't have a natural ordering.
  • The ordering imposed by a comparator c on a set of elements S is said to be consistent with equals if and only if c.compare(e1, e2)==0 has the same boolean value as e1.equals(e2) for every e1 and e2 in S

It is used to be two method in Java 7, but now there are many method in Comparator interface in Java 8. As per Java 8 This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

An element in a list can compare itself to another of its own type in only one way. using its compareTo(} method. But a Comparator is external to the element type you're comparing-it's a separate class. So you can make as many of these as you like!
Want to compare Student by id? Make a StudentIdComaparator. Sort by name? Make a StudentNameComparator.

Then all you need to do is call the overloaded sort() method that takes the List and the Comparator that will help the sort() method put things in order. The sort() method that takes a Comparator will use the Comparator instead of the element's own compareTo(} method, when it puts the elements in order. In other words, if your sort method gets a Comparator, it won't even call the compareTo() method of the elements in the list. The sort() method will instead invoke the compare() method on the Comparator.

So, the rules are:

  1. Invoking the one-argument sort(L1st 0) method means the list element'ss compareTo() method determines the order. So the elements in the list MUST Implement the Comparable Interface.
  2. Invoking sort(List 0, Comparator c)means the list elemenfs compareTo() method will NOT be called, and the Comparators compare{) method will be used Instead. That means the elements in the list do NOT need to Implement the Comparable Interface.
Example :





java.lang.Comparable java.util.Comparator
The method in the Comparable interface is declared as                                 int compareTo(ClassType type);. The method in the Comparator interface is declared as
int compare(ClassType type1, ClassType type2);.
Returns
     negative if objOne < objTwo
     zero if objOne == objTwo
     positive if objOne > objTwo
Same as Comparable
You must modify the class whose instances you want to sort. You build a class separate from the class whose instances you want to sort.
Implemented frequently in the API by: String, Wrapper classes, Date, Calendar… Meant to be implemented to sort instances of third-party classes.
Used when the objects need to be compared in their natural order. Used when the objects need to be compared in custom user-defined order (other than the natural order).
You do not create a separate class just to implement the Comparable interface You create a separate class just to implement the Comparator interface.
For a given class type, you have only that class (and that class alone) implementing the Comparable interface. You can have many separate (i.e., independent) classes implementing the Comparator interface, with each class defining different ways to compare objects.



If you know anyone who has started learning Java, why not help them out! Just share this post with them. 
Thanks for studying today!...

Wednesday, February 26, 2014

Lambda examples and Effectively Final in Java 8

In the previous post, we have checked how to use Lambda expression, what are its advantages and reason behind it's motivation, definition of function interface and its use in Lambda expression. In this post, we'll see lots of examples of Lambda with its syntax and it's other uses.

Simplest Form of Lambda expression
Replace this

new SomeInterface() {  
 @Override  
     public SomeType someMethod(args) { body }  
 }

with

(args) -> { body } 

That's what the main purpose of Lambda expression in Java 8 

Example : In this example, we'll sort a string array on the basis of its length. 

 import java.util.Arrays;  
 import java.util.Comparator;  
 public class LambdaSimplesFormExample {  
   public static void main(String[] javalatteLambda) {  
     String[] str = {"one", "two", "3", "four", "five", "sixsix", "sevennnnn", "eight"};  
     Arrays.sort(str, new Comparator<String>() {  
       @Override  
       public int compare(String s1, String s2) {  
         return (s1.length() - s2.length());  
       }  
     });  
     Arrays.sort(str, (String s1, String s2) -> {  
       return (s1.length() - s2.length());  
     });  
     for (String s : str) {  
       System.out.println(s);  
     }  
   }  
 }  

Type Inferencing in Lambda expression
Types in argument list can be omitted since Java usually already know the expected parameters types for the single method of the functional interface.
Basic Lambda expression
Type1 var1, Type2 var2 …) -> { method body }
Lambda with type inferencing
(var1, var2 …) -> { method body }

Example : In this example, we'll sort a string array by its last character, or you can use the previous example for the same purpose.

 import java.util.Arrays;  
 import java.util.Comparator;  
 public class TypeInferencingLambda {  
   public static void main(String[] javalatteLambda) {  
     String[] str = {"one", "two", "3", "four", "five", "sixsix", "sevennnnn", "eight"};  
     Arrays.sort(str, new Comparator<String>() {  
       @Override  
       public int compare(String s1, String s2) {  
         return (s1.length() - s2.length());  
       }  
     });  
     Arrays.sort(str, (s1, s2) -> {  
       return (s1.charAt(s1.length()-1) - s2.charAt(s2.length()-1) );  
     });  
     for (String s : str) {  
       System.out.println(s);  
     }  
   }  
 } 

Expression for Lambda body

  • In Lambda we can use expression instead of block
    Value of the expression will be the return value, so no explicit return statement is required.
  • If method has a void return type, then automatically no value will be returned.
  • We use expression when method body is short because of common approach.
  • Previous version
    (var1, var2 …) -> { return(something); }
    return (s1.charAt(s1.length()-1) - s2.charAt(s2.length()-1) );
  • Lambda with expression for body
    (var1, var2 …) -> something
    s1.charAt(s1.length()-1) - s2.charAt(s2.length()-1) ;
Example :  We can use the previous examples to apply this expression for Lambda. I hope, here example is not required. 


Omitting parentheses in Lambda expression

  • If method takes single arg, parentgeses optional : No type should be used: you must let Java infer the type
  • Previous version
    (varName) -> someResult()
  • Lambda with parentheses omitted
    varName -> someResult()
Example : In this example, we'll try to use Java 8 inbuilt functional interface i.e, IntUnaryOperator . But there are certain forms of functional interfaces that are widely, commonly useful, which did not exist previously in the JDK. A large number of these interfaces have been added to the new java.util.function package. Here are a few:
  • Function<T, R> - take a T as input, return an R as ouput
  • Predicate<T> - take a T as input, return a boolean as output
  • Consumer<T> - take a T as input, perform some action and don't return anything
  • Supplier<T> - with nothing as input, return a T
  • BinaryOperator<T> - take two T's as input, return one T as output, useful for "reduce" operations
  • IntConsumer - take an int as input, perform some action and don't return anything
  • IntUnaryOperator - an operation on a single int-valued operand that produces an int-valued result



If you still difficulty in understanding this example, please first have a look on this user defined functional interface example in my previous post  that help you to understand the above program and IntUnaryOperator interface. 
A Lambda Expression Is an Anonymous Method
There are few rules for lambda expression to be compatible with functional interface
  1. The lambda expression must return a result that is compatible with the result of the functional interface method.
  2. If the result is void, the lambda body is void-compatible.
  3. If a value is returned, the lambda body is value-compatible.
  4. The lambda expression signature must be the same as the functional interface method's signature.
  5. The lambda expression can throw only those exceptions for which an exception type or an exception supertype is declared in the functional interface method's throws clause.

Example of above rules :







Exception Handling in Lambda
  • A lambda expression body must not more throw exceptions that are not specified in the functional interface.
  • If lambda expression throws an exception, then throws clause of the functional interface must declare the same exception or its subtype.
Examples :



If the same exception is thrown by lambda expression which is define by the functional interface, the compiler error will resolved but when you invoked the Lambda expression again compiler error message will be shown because exception is not handled in main method.




Lambda Expressions in return Statements
A lambda expression can be used in a return statement. The return type of the method in which a lambda expression is used in a return statement must be a functional interface.





Lambda Expressions as Target Types
Lambda expressions themselves can be used as target types for inner lambda expressions.
In the following example:
  • The print1() method in PrintInterface returns an Object, but the square() method in SquareInterface doesn't have a return type.
  • The target type of the inner lambda expression in the LambdaTargetType class is a SquareInterface, and the target type of the outer lambda expression is PrintInterface. 
  • The target type is inferred from the context, which is an assignment statement to a reference variable of type PrintInterface<SquareInterface>




The inner lambda expression, () -> System.out.println("Hello Java latte : "+(x*x));, is inferred to be of type SquareInterface because the parameter list is empty and result is int; the anonymous method signature and result are the same as the square() method in the SquareInterface interface.
The outer lambda expression, () -> SquareInterface, is inferred to be of type PrintInterface<SquareInterface> because the print1() method in PrintInterface<V> does not declare any formal parameters and the result type is type parameter V.

Another Example of above case, in this example we'll use Callable<V>  and Runnable interface.
Callable<V>
V call() : Computes a result, or throws an exception if unable to do so.

Runnable
void run() : When an object implementing interface Runnable is used to create a thread, starting the thread causes the object's run method to be called in that separately executing thread.

Lambda Expressions in Array Initializers
Lambda expressions can be used in array initializes, but generic array initializes cannot be used.
As we know about Callable functional interface and its method. We use Callable interface for initializing array or we can create our own functional interface for the same purpose.

For example, following will generate error
Callable<String>[] c=new Callable<String>[]{ ()->"a"}; 
A compiler error—Cannot create a generic array of Callable<String>








Casting Lambda Expressions
Sometimes the target type of a lambda expression can be ambiguous. For example, in the following assignment statement, a lambda expression is used as method argument to the Privilege.doSomething method.
The target type of the lambda expression is ambiguous because more than one functional interface— test1 and test —could be the target type of the lambda expression.
c
What we need to do is 


Class AccessController has such two method where method argument is functional interface and in such case we need to do the casting when using lambda expression in such functions.



Lambda Expressions in Conditional Expressions
Lambda expressions can be used in ternary conditional expressions, which evaluate one of the two operands based on whether a boolean condition is true or false.




Lambda Expression as Parameter Names

Refer to first example of this post
     Arrays.sort(str, (String s1, String s2) -> {  
       return (s1.length() - s2.length());  
     });  





Local Variables in Lambda Expressions

  • A lambda expression does not define a new scope; the lambda expression scope is the same as the enclosing scope.
  • If a lambda expression body declares a local variable with the same name as a variable in the enclosing scope, a compiler error gets generated.
  • A local variable, whether declared in the lambda expression body or in the enclosing scope, must be initialized before being used.
  • To demonstrate this, declare a local variable in the enclosing method: int size; Use the local variable in the lambda expression.



Final or Effectively Final Local Variables
Lambdas can refer to local variables that are not declared final but are never modified. This is known as "effectively final". Where it would have been legal to declare them final.

Example of effectively final


  • You can still refer to mutable instance variables.
  • "this" in a lambda refers to main class, not inner class that was created for the lambda. There is no OuterClass.this. 
  • The this and super references in a lambda body are the same as in the enclosing context, because a lambda expression does not introduce a new scope, which is unlike the case with anonymous classes.

Let's see an example where we modified the variable in Lambda expression. Compiler will give error - local variables referenced from a lambda expression must be final or effectively final .

The variable i can be declared final as follows.
final size i=10;
Otherwise, the variable must be effectively final, which implies that the variable cannot be assigned in the lambda expression. Method parameter variables and exception parameter variables from an enclosing context must also be final or effectively final.
  • With explicit declaration
    final int size = somevalue;
    doSomething(someArg -> use(size));
  • Effectively final
    int size = somevalue;
    doSomething(someArg -> use(size));


If you know anyone who has started learning Java, why not help them out! Just share this post with them. 
Thanks for studying today!...

Thursday, February 13, 2014

Factory method Design Pattern in Java

In this post, we'll see how Factory method Design Pattern come into picture, what advantages it will provide and how it help in implementing loose coupling concept.

Below picture shows Car factory that produce different car depending on it's feature and model. For instance, it produces BMW 1 series, BMW 2 Series, BMW M3 etc. Whatever order we placed for car, factory will produce.

This same concept applies to Factory Design pattern.




From the name itself you can identify what does this pattern do. Factory method pattern is used for creating object based on different parameters. If we ask for BMW M3, the factory will produce BMW M3; if we ask for Ferrari, factory will produce Ferrari.

The factory method pattern is an object-oriented creational design pattern to implement the concept of factories and deals with the problem of creating objects (products) without specifying the exact class of object that will be created. The essence of this pattern is to "Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate.


How Factory Design pattern come into picture
When you use "new" you are certainly instantiating a concrete class, so that's is definitely an implementation, not an interface. Typing a code to a concrete class can make it more fragile and less flexible. How? let's see an example

interface Car{  
      void paintColor(String color);  
 }  
 class BMW implements Car{  
      @Override  
      public void paintColor(String color) {  
           System.out.println("Red");  
      }  
 }  
 class Ferrari implements Car{  
      @Override  
      public void paintColor(String color) {  
           System.out.println("Green");  
      }  
 }  
 class Audi implements Car{  
      @Override  
      public void paintColor(String color) {  
           System.out.println("Yellow");  
      }  
 }  
 public class CreateCar {  
      Car createCar(String carType){  
           Car c = null;  
           if(carType.equals("Audi")){  
                c = new Audi();  
           }else if(carType.equals("BMW")){  
                c = new BMW();  
           }else if(carType.equals("Ferrari")){  
                c = new Ferrari();  
           }  
           return c;  
      }  
 }

Here we have got several class being instantiated and the decision of which to instantiate is made at run time depending on condition.
When it comes time for change or extensions  you'll need to open this code and examine what need to be added or deleted. This kind of code ends up in several part of the application making maintenance and update more difficult.

By coding to interface, you can free yourself from a lot of changes that might happen to a system down the road. How? 
If your code is written to interface, then it work with any new class implementing that interface through polymorphism. But, when you have code that make a lot of concrete class, you are looking for trouble because that code may have to changed as new concrete classed are added. It means this code is not "closed for modification".

public class PreFactoryPatternDemo {  
      Car createCar(String carType){  
           Car c = null;  
           if(carType.equals("Audi")){  
                c = new Audi();  
           }else if(carType.equals("BMW")){  
                c = new BMW();  
           }else if(carType.equals("Ferrari")){  
                c = new Ferrari();  
           }else if(carType.equals("volkswagen")){  
                c = new Ferrari();  
           }else if(carType.equals("chevrolet")){  
                c = new Ferrari();  
           }else if(carType.equals("hyundai")){  
                c = new Ferrari();  
           }else if(carType.equals("Maruti")){  
                c = new Ferrari();  
           }  
           return c;  
      }  
 }

Now here come the first design principle : identify the aspects that vary and separate them from what stays the same.
But now we know that what is varying and what isn't, it's probably time to encapsulate it.

Encapsulating Object creation
We will move the following code out, then place that code in an object that is only going to worry about how to create car. If anybody object need a car object created, this is object to come in.

Car c;  
           if(args[0].equals("Audi")){  
                c = new Audi();  
           }else if(args[0].equals("BMW")){  
                c = new BMW();  
           }else if(args[0].equals("Ferrari")){  
                c = new Ferrari();  
           }else if(args[0].equals("volkswagen")){  
                c = new Ferrari();  
           }else if(args[0].equals("chevrolet")){  
                c = new Ferrari();  
           }else if(args[0].equals("hyundai")){  
                c = new Ferrari();  
           }else if(args[0].equals("Maruti")){  
                c = new Ferrari();  
           }  

We got a name for this new object; we call it a Factory.
Now our code look like
 class CarFactory{  
      public Car defaultCar(String type){  
           Car c = null;   
           if(type.equals("Audi")){   
                c = new Audi();   
           }else if(type.equals("BMW")){   
                c = new BMW();   
           }else if(type.equals("Ferrari")){   
                c = new Ferrari();   
           }else if(type.equals("volkswagen")){   
                c = new Ferrari();   
           }else if(type.equals("chevrolet")){   
                c = new Ferrari();   
           }else if(type.equals("hyundai")){   
                c = new Ferrari();   
           }else if(type.equals("Maruti")){   
                c = new Ferrari();   
           }   
           return c;   
      }  
 }

It looks like we are just pushing the problem off to another object. Yes, you are right. One thing to remember is that CarFactory may have different client.
We have only seen the createCar method; however, there may be different class TyreCar that uses the factory to get car for tunning tyre performance.
We might also have a EngineCar class that tune the engine other than CreateCar. So TyreCar, EngineCar also need instance of car instead of writing the object creation each class, they are use Factory class.

Final Code will look like

interface Car{  
      void setPaint(String color);  
      void setEngine(String engine);  
      void setTyre(String tyre);  
 }  
 class Audi implements Car{  
      public void setPaint(String color) {  
           System.out.println("Black color for Audi");  
      }  
      public void setEngine(String engine) {  
           System.out.println("1000cc Engine for Audi");  
      }  
      public void setTyre(String tyre) {  
           System.out.println("Apollo tyre for Audi");  
      }  
      public String toString(){  
           return "Black Audi with 1000c";  
      }  
 }  
 class BMW implements Car{  
      public void setPaint(String color) {  
           System.out.println("Red color for BMW");  
      }  
      public void setEngine(String engine) {  
           System.out.println("800cc Engine for BMW");  
      }  
      public void setTyre(String tyre) {  
           System.out.println("Apollo tyre for BMW");  
      }  
      public String toString(){  
           return "Red BMW with 800cc";  
      }  
 }  
 class Ferrari implements Car{  
      public void setPaint(String color) {  
           System.out.println("Yello color for Ferrari");  
      }  
      public void setEngine(String engine) {  
           System.out.println("1800cc Engine for Ferrari");  
      }  
      public void setTyre(String tyre) {  
           System.out.println("Apollo tyre for Ferrari");  
      }       
      public String toString(){  
           return "Yello Ferrari with 1800cc";  
      }  
 }  
 class CarFactory{  
      public static Car defaultCar(String name){  
           Car c = null;  
           if(name.equals("Audi")){  
                c = new Audi();  
           }else if(name.equals("BMW")){  
                c = new BMW();  
           }else if(name.equals("ferrari")){  
                c = new Ferrari();  
           }  
           return c;  
      }  
 }  
 public class a{  
      public static void main(String javalatte[]){  
           Car c;  
           c = CarFactory.defaultCar("Audi");  
           c.setTyre("BridgeStone");  
           c = CarFactory.defaultCar("BMW");  
      }  
 }



  • Factory patterns are examples of creational patterns.
  • Creational patterns abstract the object instantiation process.They hide how objects are created and help make the overall system independent of how its objects are created and composed.
  • Class creational patterns focus on the use of inheritance to decide the object to be instantiated -Factory Method
All OO languages have an idiom for object creation. In Java this idiom is the new operator. Creational patterns allow us to write methods that create new objects without explicitly using the new operator. This allows us to write methods that can instantiate different objects and that can be extended to instantiate other newly-developed objects, all without modifying the method's code!


Applicability
  • A class can't anticipate the class of objects it must create
  • A class wants its subclasses to specify the objects it creates
Factory design pattern used in Java standard library

Based on different parameter, getInstance() returns a different instance of Calendar
java.util.Calendar – getInstance()
java.util.Calendar – getInstance(TimeZone zone)
java.util.Calendar – getInstance(Locale aLocale)
java.util.Calendar – getInstance(TimeZone zone, Locale aLocale)

java.text.NumberFormat – getInstance()
java.text.NumberFormat – getInstance(Locale inLocale)




If you know anyone who has started learning Java, why not help them out! Just share this post with them. 
Thanks for studying today!...

Tuesday, February 11, 2014

The Data Access Object (DAO) Design Pattern

In this post, we'll see the basic of DAO Design Pattern, how to implement and what advantages it provide and it's use.


Suppose you are at Disney land with your family or friends and you decide to take a ride on carousel. You see a big panel with so many buttons for operating the carousel.You ask the operator to start the carousel, adjusts it speed and stop it. The operator who know how to use panel, follows your instructions. He is providing you abstraction from the complicated operating panel. In fact, if you go to different carousel in other fair, you can instruct its operartor in the same way and the operator will follow your instructions in the same way even thought his panel is different from that of the first carousel. In essence, you and your family enjoy can take a ride on any carousel without understanding its operating panel because the knowledge to operate the machine is abstracted by the operator.
The Data Access Object pattern provide you abstraction in the same as carousel operator does in providing to their customers.






















In real-life projects, you will encounter situation in which you want to make your data persist. You might use flat files, XML files, RDBMS etc. In such situations, you can use DAO design pattern. This design pattern abstract the details of the underlying persistence mechanism whether you use mysql or oracle and offers you an easy-to-use interface for implementing the storing the data. The DAO pattern hides the implementation detail of the data source from its clients, thereby introducing loose coupling between your core business logs and your storage mechanism.
This will help you to move from one type store to another storage mechanism.

Let’s examine the structure of the pattern.


Apart from the above classes (Client, DAO, TransferObject and DataSource), there could be one more class for this pattern - DAOFactory. You may have multiple DAO object corresponding to different types of objects you want to store such as XML, MYSQL, ORACLE. This factory will define one method for each DAO object.

Let's see with the help of example what we have studied above. In this Paint example, we have a circle class that you want to store in persistance data store. For this we'll create a CircleTransfer object with setter and getter methods.
/*  
  * Transfer Object as per diagram  
  */  
 public class CircleTransfer{  
      private int x;  
      private int y;  
      private int radius;  
      void setX(int x){  
           this.x=x;  
      }  
      void setY(int y){  
           this.y=y;  
      }  
      int getX(){  
           return x;  
      }  
      int getY(){  
           return y;  
      }  
      void setRadius(int radius){  
           this.radius=radius;  
      }  
      int getRadius(){  
           return radius;  
      }  
 }  
 /*  
  * DAO as per Diagram  
  */  
 interface CircleDAO{  
      public void insertCircle(CircleTransfer circle);  
      public CircleTransfer findCircle(int x,int y);  
      public void deleteCircle(int x,int y);  
 }  
 /**  
  * DataSource as per Diagram  
  * Oracle Implementation  
  */  
 public class RDMSDAO implements CircleDAO{  
      @Override  
      public void insertCircle(CircleTransfer circle) {  
           // insertCircle implementation as per Oracle database  
      }  
      @Override  
      public CircleTransfer findCircle(int x, int y) {  
           // findCircle implementation  
           return null;  
      }  
      @Override  
      public void deleteCircle(int x, int y) {  
           // deleteCircle implemenation  
      }  
 }  
 /**  
  * DataSource as per Diagram  
  * MySql Implementation  
  */  
 public class MYSQLDAO implements CircleDAO{  
      @Override  
      public void insertCircle(CircleTransfer circle) {  
           // insertCircle implementation as per MYSQL database  
      }  
      @Override  
      public CircleTransfer findCircle(int x, int y) {  
           // findCircle implementation  
           return null;  
      }  
      @Override  
      public void deleteCircle(int x, int y) {  
           // deleteCircle implemenation  
      }       
 }  
 /*  
  * Factory   
  */  
 public class DAOFactory{  
      public static CircleDAO getCircleDao(String sourceType){  
           switch(sourceType){  
           case "Oracle":  
                return new RDMSDAO();  
           case "mysql":  
                return new MYSQLDAO();  
           }  
           return null;  
      }  
 }  
 /*  
  * Core Business logic  
  */  
 public class Circle{  
      private int x,y,r;  
      Circle(int x,int y, int r){  
           this.x=x;  
           this.y=y;  
           this.r=r;  
      }  
      public CircleTransfer getCircleTransferObject(){  
           CircleTransfer c = new CircleTransfer();  
           c.setRadius(r);  
           c.setX(x);  
           c.setY(y);  
           return c;  
      }  
 }  
 /*  
  * Client  
  */  
 public class DaoPatternDemo {  
      public static void main(String[] javalatte) {  
           Circle c = new Circle(2,2,4);  
           CircleTransfer ct = c.getCircleTransferObject();  
           CircleDAO cDao = DAOFactory.getCircleDao("oracle");  
           cDao.insertCircle(ct);  
      }  
 }  
The Circle class belongs to your core business logic, the Circle class contains a method—getCircleTransferObject()—that returns the CircleTransfer object with the required data.
You define the CircleDAO interface with three methods commonly used with data sources.
The RDBMSDAO implements CircleDAO with a concrete implementation to access the RDBMS data source.
The CircleTransfer object plays a data carrier role between the main() method (which is acting as a Client) and DAO implementation (i.e., the RDBMSDAO class).

Here are the benefits of the DAO design pattern:
  • The pattern introduces an abstraction: the DAO hides the implementation details of the actual data source from the core business logic. The business logic need not know about the nitty-gritty of the data source, which results in easy-to-understand, less complicated code.
  • The pattern separates the persistence mechanism from rest of the application code and puts it together in one class specific to one data source. This centralization enables easier maintenance and easier bug-tracing.
  • It is quite easy to extend support for other data sources using this pattern. For instance, if you want to provide support for the XML-based repository in the FunPaint application, this can be achieved by defining a new class (say XMLDAO). This new class will implement your CircleDAO interface, such that you do not need to change the way you access the data source. The only thing that needs to be changed is the parameter you pass to DAOFactory to create a DAO.



If you know anyone who has started learning Java, why not help them out! Just share this post with them. 
Thanks for studying today!...