Translate

Tuesday, October 30, 2012

Design Patterns(Creational Design Patterns)


Design Patterns



                       Design patterns are the set of rules as best solutions for re-occurring problems of application development. Senior Software Engineer’s prepares Design Patterns based on experience. Junior Software Engineers will use them in project implementation most of the Design Patterns are give by a team called GOf.

                        The worst solutions for re-occurring problems are for application development is called anti patterns every software technologies contain Design Patterns to utilize those software technologies more effetely.

Design Patterns are the best practices of application development by using software technologies more effetely.

Basic Design Patterns or Creational Design Patterns.:

  1. Factory Method
  2. Singleton Java class
  3. Factory
  4. Abstract Factory
  5. Builder
  6. Proto Type
  7. IOC(Inversion of Control)/DI(Dependence Injection)
  8. Template Method
  9. Value Object (Or) Data Transfer Object
  10. Adapter Class
  
  1. Factory Method:

A method in a java class that is capable of constructing its own java class object is called Factory Method.

Problem: - We can’t create object of a java class out side the class. When class contain only private constructer.

Solution: - Add Factory Method in that class rules implemented to factory method.
          
    1. Recommended to take method as public static method
    2. Return type of method must be a class name..

    

  Class Test                                         Test t = new Test ();    -------à  X
   {             
       private Test ()                               Test t = Test.m1();      -------à |/
       {
          …………..
       }
       Public static Test m1 (); -à Factory Method
 }

Real Time Example:

          Thread t = Thread.curentThread ();
   
           String s = String.valueOf (10);

           Class c = Class.forName (“XYZ”);

2. Singleton Java Class:

            A Java class that allows creating only one object per jvm is called singleton java class.

Problem: - Creating multiple objects for java class having same data. It wastes the memory and time of object creation and distraction.

Solution: - Make java class as singleton java class. So that only one java class object will be created and that object can be utilized for multiple number of times.

Rules: -
1.      Class must have a factory method (“static having singleton logic”)
2.      Class must have private constructor

Note: - private constructor is very important in singleton java class to close all the doors of object creation of except throw factory method that contains singleton logic.

Class SingletonTest
{
   private static SingletonTest n = null;

   private SingletonTest()
   {
            System.out.println(“Constructor”);
  }
// Factory method having singletone logic
   public static SingletonTest create()
  {
      //single tone logic
       if(n == null)
        n= new SingletonTest();
       return n;
 }
}

Class Demo
{
    public static void main(String args[])
    {
         SingletonTest.create ();
         SingletonTest.create ();
         SingletonTest.create ();
        SingletonTest.create ();
   }
}

à In single computer we can see multiple jvm’s. When multiple java applications are executing simultaneously or parallel.

>java class name.

Starts JVM process to execute the given java application.

3. Factory Pattern:

            Factory Design pattern all about logic return in a java method to create one of the multiple sub class object based on the data you supplied.

            Ex: - When we don’t know the return object class name while designing any java method we generally take java.lang.Object class as return type. This is nothing but implementing Factory Design Patterns,

       Public Object getAttribute (String name);
 

       session.setAttribute (“name”,”chandra”);

        session.setAttribute (“age”, new Integer (35));

       String s1 = (String) session.getAttribute (“name”);

       Integer i1 = (Integer) session.getAttribute (“age”);

Example:-

//Base Class
Class Person
{
    public String name;
    private String gender;

     public String getName ()
     {
          return name;
     }
     public String getGender ();
     {
          return gender;
      }
 }

//Child class

Class Male extend Person
{
    public Male (String fullName)
    {
          System.out.println (“Hello Mr. “+fullName);
    }
}

Class Female extend Person
{
    public Male (String fullName)
    {
          System.out.println (“Hello Miss “+fullName);
    }
}
//Factory method class

Public Class FactoryTest
{
   public static void main(String args[])
   {
            FactoryTest factory = new FactoryTest ();
 
            Factory.getPerson (args [0], args [1]);
   }
}
public Person getPerson (String name, String gender)
{
   if (gender. Equals (“M”))
   
        return new Male (name);
   else
        return new Female (name);
   else
        return null;
 }
}//end of class

 à In the above code getPerson(------,------) the logic of given based on factory design pattern because it may create one of the Male or Female class object( Sub classes of Person class) based on the data we supplied to the method as argument but no sub class name is mention as return type the supper class. Person to satisfy the requirement of any one sub class object.

4. Abstract Factory:

            It is provides one level abstraction on factory designed pattern. By Isolating the names of several sub classes for whom objects are created based on the data you supplied. So that while working with various logic’s of these sub classes. We need not to know the names of the sub classes.

Example Code:-

Interface ABC
{
    public void xyz ();
}

Class Test1 implement ABC
{
   public Test1()
   {
      System.out.println(“Test1”);
  }
  public void xyz()
  {

      System.out.pringln(“xyz of Test1”);
 }
}//end of class Test1


Class Test2 implement ABC
{
    public Test2()
   {
        System.out.println(“Test2”);
   }
   public void xyz()
   {
      System.out.println(“xyz of Test2”);
   }
}//end of class Test2

Class Demo
{
   public static ABC m1(String name)
   {
       if(name.equals(“a”))
            return new Test1();
       elseif(name.equals(“b”))
            return new Test2();
       else
            return null;
    }
}

//client Code

public Class AbstractFactoryTest
{
     public static void main(String args[])
     {
         ABC Ab1 = Demo.m1(args[0]);
         Ab1.xyz();
     }
}

à In the above client code Demo.m1() returns one of the Test1 or Test2 objects based on the data we supplied at run time but in order to utilize logics of these returned objects we need not to know the class names Test1 and Test2. We can call the logic by just referring objects with interface reference variable that is implemented by both Test1 and Test2 classes.

Q) What is the difference between Factory and Abstract Factory Design Patterns?

R) Factory gives one of the several sub class objects. In order to use logic of any subclass object we must know the name of the subclass. Where as Abstract Factory logic also gives one of the several subclass object based on the input data. We pass but while using logics off these subclass objects we need not to know the names of the concrete class or subclasses.

Abstraction means hiding the implementation details from the client.

5. Proto Type Design Pattern:

            It is the process of creating cloned object of a existing object.

Problem: - If you create duplicate object of existing object manually or separately. It needs lot of JVM resources.

Solution:- Create duplicate object by using clone method of java.lang.object class

            The java object becomes ready for cloning when class of that object implements java.lang.Clonable interface. It is a marker interface because it apple’s special behavior on the object that is making object ready for cloning.

à Implementing proto type design pattern is nothing but creating object through clone.

Class Test implement Clonable
{
    int a,b;
    public Test(int x,int y)
    {

            a=x;
            b=y;
            System.out.println(“constructor “);
     }
     public Object m1()
     {
            try
            {
                        return super. clone();
                    // logic that is implementing proto type design pattern
           }catch(Exception e)
           {
                        e.printStackTrace();
                        return null;
            }
       }
      public String toString()
       {
            return “a= “+ a + “b=” + b;
       }
      public static void main(String args[])
      {
            Test t = new Test(10,20);
            System,out.println(“Data of Object is “ + t.toString());
            Test t1 = (Test)t.m1();
            System.out.println(“Data of object t1 is “+t1.toString());
            t.a =30;
            System.out.println(“Data of object t is “+t.toString());
            System.out.println(“Data of object t is “+t1.toString());
      }//main method close
}//end of the class

6. Builder Design Pattern:-

            The Builder Design Pattern is the process of constructing complex object from simple object step by step but it hides the construction of individual objects in the process of constructing main object. So that the program can create main object are can use logic of main object a without varying about the depended object constructing and their logic.

Ex:-

Interface Item
{
            public int price ();
}
Class Burgger implements Item
{
            public int price ()
            {
                        return 25;
            }
}

Class Frides implements Item
{
            public int price ()
            {
                        return 15;
            }
}

Class Drink implements Item
{
            public int price ()
            {
                        return 30;
            }
}

public Class MealBuilder
{
            public int calcPrice ()
            {
            return new Burger ().price () + new Frides ().price () +new Drink ().price ();
           }
           public static void main (String[] args)
            {
                        MealBuilder ms = new MealBuilder ();
                        Int val = ms.calcPrice ();
                        System.out.println (“Meal Price value “+ val);
            }
}//end of the class

In the above code the calcPrice () of Meal Builder class gives the total meal price by knowing the price of each item that is used in the meal. So that the client is not bothered about knowing price of each item when he ordered a meal. That is nothing but builder design pattern.

7. Template Design Pattern:

            Template means readily available wizard. Instead of calling multiple methods in a sequence by recommending method names to complete a task it is recommended it is recommended to combine all these methods called in one method and use one method to complete the task. This is called Template Design Pattern.


Problem:                                                                      solution:

Task 1   x();                                                      public int xyz()
              Y();                                                     {
              Z()                                                          x();
              A()                                                          y();
              B()                                                          z();
                                                                             A();
                                                                              B();
                                                                         }
Real Time Ex:-  Request Processor class is a helper class for Action Servlet in this class nearly 16 processXXX() are there to process the request coming to Action Servlet actually ActionServlet is called all the 16 methods is sequence by creating object for Request process class to complete request processing. But ActionServlet calles only one method of request process class that is process(), Because this process internally calles 16 processXXX() by becoming template methods.

Processor precess(request, response)

8. Adapter Design Pattern:

            Adapter means taking others responsibility. When class is not interest to provide implementation al the methods available in the interface make your class containing the from adapter class of that interface. So that you will get freedom to just override only those methods in while we are inset in because adapter class provide null method (empty method) definition for all the methods available in the interface,

Ex:- Java.awt.EventWindowAdapter class is an Adapter class for java.awt.Event.WindowListener Interface.

Problem:-

Public interface xyz
{
            public void x();
            public void y();
            public void z();
}

Class Test1 implements xyz
{
             public void x()
            {
                …………..
                …………..
               ……………
            }
            public void y()
            {}
            public void z()
            {}
}


Class Test2 implements xyz
{
            public void z()
            {
                        ……………….
                        ………………
            }
}

Solution:

Public Class Demo implements xyz
{
            public void x();
            public void y();
            public void z();
}

public Class Test1 extends Demo
{
            public void x()
            {          
                        …………….
                        …………….
            }
}

public Class Test2 extends Demo
{

            public void z();
            {
                        ………………….
                        …………………
            }
}

           
9. Value Object (Or) Data Transfer Design Pattern:

            While sending huge amount of data values between two layer’s of project instead of sending these values for multiple number of times as individuals it is for multiple number of times it is recommended to combined all these values into single object than send to another layer. This process is called implementation value object design pattern. This reduces number of round trips between layers and it also becomes easy to recive data and to send data.
            Executing select sql query, getting Result Set object and transferring data of the Result Set object to list data structure like Array List and searching this list data structure to another layer is called Value Object Design Pattern implementation in web 2.0 EJB Communication the EJB sends huge amount of values to web Layer for presentation with the support of the Design Pattern implementation.

            In Struts development application multiple values of a form(View Layer) will be send to Action Class(Model Layer) by combining into single object called into Form Bean class object. This process is nothing but simple dealing with value object Design Patterns.

  1. IOC/DI:

If main object spends time to get dependent values by performing search or lookup operation then it is called dependency lookup.

            Ex;- if servlet or EJB components gets data source object by performing search or lookup operations on naming service using JNDI then it is called dependency lookup. When main object is ready if the under laying frame work or container software automatically assignes depended values to main object then it is called dependency injection or inversion of control. In Struts the way Frame Work Software auto matically written form data to form bean class object by calling setXXX() methods is called DI / IOC.

            Ex:- When Object is created the way JVM executes one of the existing constructer as to assign intial values to object as depended values comes under dependency injestin. The latest frame work software like spring structs and the latest EJB 3.0 are given based on DI.
           

            End of The Creational Design Pattern Here Next post Web Design Patterns Please post comments. So that I can update here.

  



No comments: