Factory Method Pattern


Factory Method Pattern:

  • Problem: Using new keyword we can not create object with flexibility and by applying restrictions.
  • Solution: Use Factory pattern (or) Factory method.
  • By defining a abstract class or an interface but let the subclass  decide which class object to instantiate.
  • A method of a class capable of constructing and returning its own class object or other class object is called "factory method".
  • There are two types of factory methods.
  1. Static factory method.
  2. Instance factory method.

 1.Static Factory method:

  • A static method defined to construct and return object of same class or different is known as static factory method.
  • Some of the pre defined static factory methods are as follows.
  1. Thread th= Thread.currentThread();
  2. Class c=Class.forName();
  3. Runtime rt=Runtime.getRuntime();
  4. Calendar c=Calendar.getInstance();

2.Instance Factory method:

  • A non static method defined to construct and return object of same class or different is known as instance factory method.
  • Some of the pre defined instance factory methods are as follows.
  1.  String s= new String("instance of");
     String s1=s.concat("java");
  2. StringBuffer sb=new StringBuffer("instance of");
    sb=sb.subString(0,2);
  3. Date d= new Date();
    String s=d.toString();
Program on Factory method / Factory Design pattern:

Step 1: create an interface:

  1. package com.instanceofjavaforus;
  2.  
  3. public interface Vehicle {
  4.  
  5.  public void engine();
  6.  
  7. }
     

 Step 2: create a Two Wheeler class which implements vehicle interface:

  1. package com.instanceofjavaforus;
  2.  public class TwoWheeler implements Vehicle {
  3.  
  4.    @Override
  5.     public void engine() {
  6.         System.out.println("Two Wheeler");
  7.     }
  8.  
  9. }

Step 3:: create a Four Wheeler class which implements vehicle interface:

  1. package com.instanceofjavaforus;
  2.  public class FourWheeler implements Vehicle {
  3.  
  4.    @Override
  5.     public void engine() {
  6.         System.out.println("FourWheeler");
  7.     }
  8.  
  9. }

Step 4: create a SixWheeler class which implements vehicle interface:

  1. package com.instanceofjavaforus;
  2.  public class SixWheeler implements Vehicle {
  3.  
  4.    @Override
  5.     public void engine() {
  6.         System.out.println("SixWheeler");
  7.     }
  8.  
  9. }

Step 5: create a TestEngine class which is having factory method:

  1. package com.instanceofjavaforus;
  2.  public class TestEngine {
  3.  public Vehicle getVehicle(String venname){
  4.      if(venname==null){
  5.             return null;
  6.        }else if(venname.equalsIgnoreCase("TwoWheeler")){
  7.             return new TwoWheeler();
  8.         }else if(venname.equalsIgnoreCase("FourWheeler")){
  9.             return new FourWheeler();
  10.         }else if(venname.equalsIgnoreCase("SixWheeler")){
  11.             return new SixWheeler();
  12.         }
  13.     
  14.         return null;
  15.     }
  16. }

Step 6: create a FactoryDemo class:

  1. package com.instanceofjavaforus;
  2.  public class FactoryDemo {
  3.   public static void main(String args[]){
  4.  
  5.      TestEngine te= new TestEngine();
  6.  
  7.         Vehicle vehcle1=te.getVehicle("TwoWheeler");
  8.        vehcle1.engine();
  9.  
  10.         Vehicle vehcle2=te.getVehicle("FourWheeler");
  11.         vehcle2.engine();
  12.  
  13.         Vehicle vehcle3=te.getVehicle("SixWheeler");
  14.          vehcle3.engine();
  15.  }
  16. }

  1. OutPut:
  2. TwoWheeler
  3. FourWheeler
  4. SixWheeler

Design patterns in java


Design patterns:

  • Pattern means set of guide lines.
  • Design patterns are solutions to commonly reoccurring problems in software development.
  • Design patterns are well proven solutions to common software problems.
  • Design patterns are best practices to use software technologies effectively in application development.  
  • Design patterns used in analysis and requirement  phase of  SDLC.
  • Design patterns can be implemented by using programming language.

Advantages:

  • Reusable.
  • These are already defined solutions to common re occurring problems so it reduces time.
  • They are already defined so Easy to understand and debug.

Categorization:

  • These are categorized into two parts.
  1. Java SE Design patterns.
  2. Java EE Design patterns.

Java SE Design patterns: 

  •  In Java SE there are mainly three types.

1.Creational Design patterns:

  1. Factory Pattern
  2. Abstract Factory Pattern
  3. Singleton Pattern
  4. Prototype Pattern
  5. Builder Pattern.

2.Structural Design patterns:

  1. Adapter Pattern
  2. Bridge Pattern
  3. Composite Pattern
  4. Decorator Pattern
  5. Facade Pattern
  6. Flyweight Pattern
  7. Proxy Pattern

3.Behavioral Design patterns:

  1. Chain Of Responsibility Pattern
  2. Command Pattern
  3. Interpreter Pattern
  4. Iterator Pattern
  5. Mediator Pattern
  6. Memento Pattern
  7. Observer Pattern
  8. State Pattern
  9. Strategy Pattern
  10. Template Pattern
  11. Visitor Pattern
Read More:
Factory pattern


Sort ArrayList in descending order

Descending order:

  1. package com.instanceofjavaforus;
  2. import java.util.ArrayList;
  3.  import java.util.Collections;
  4. import java.util.Comparator;
  5.  
  6. public class SortArrayListDesc {
  7.  
  8.      public static void main(String[] args) {
  9.  
  10.             //create an ArrayList object
  11.             ArrayList arrayList = new ArrayList();
  12.  
  13.             //Add elements to Arraylist
  14.             arrayList.add(1);
  15.             arrayList.add(2);
  16.             arrayList.add(3);
  17.            arrayList.add(4);
  18.             arrayList.add(5);
  19.             arrayList.add(6);
  20.  
  21.             /*
  22.            Use static Comparator reverseOrder() method of Collections 
  23.         utility class to get comparator object
  24.            */
  25.  
  26.          Comparator comparator = Collections.reverseOrder();
  27.  
  28.           System.out.println("Before sorting  : "  + arrayList);
  29.         
  30.  
  31.            /*
  32.               use
  33.               static void sort(List list, Comparator com) method of Collections class.
  34.             */
  35.  
  36.             Collections.sort(arrayList,comparator);
  37.             System.out.println("After sorting  : + arrayList);
  38.  
  39.        }
  40.     }
     

  1. OutPut:
  2. Before sorting  : [1, 2, 3, 4, 5, 6]
  3. After sorting  : [6, 5, 4, 3, 2, 1]
     

Ascending order:


  1. package com.instanceofjavaforus;
  2. import java.util.ArrayList;
  3.  import java.util.Collections;
  4. import java.util.Comparator;
  5.  
  6. public class SortArrayListAsc{
  7.  
  8.      public static void main(String[] args) {
  9.  
  10.             //create an ArrayList object
  11.             ArrayList arrayList = new ArrayList();
  12.  
  13.             //Add elements to Arraylist
  14.             arrayList.add(10);
  15.             arrayList.add(4);
  16.             arrayList.add(7);
  17.            arrayList.add(2);
  18.             arrayList.add(5);
  19.             arrayList.add(3);
  20.  
  21.           
  22.  
  23.           System.out.println("Before sorting  : "  + arrayList);
  24.         
  25.  
  26.            /*
  27.               use
  28.               static void sort(List list) method of Collections class.
  29.             */
  30.  
  31.             Collections.sort(arrayList);
  32.             System.out.println("After sorting  : + arrayList);
  33.  
  34.        }
  35.     }
     



  1. OutPut:
  2. Before sorting  : [10, 4, 7, 2, 5, 3]
  3. After sorting  : [2, 3, 4, 5, 7, 10]

Arraylist add element at specific index

  1. package com.instanceofjavaforus;
  2. import java.util.ArrayList;
  3.  
  4. public class AddElementAtSpecifiedIndex {
  5.  
  6.     public static void main(String[] args) {
  7.  
  8.        //create an ArrayList object
  9.         ArrayList arrayList = new ArrayList();
  10.  
  11.         //Add elements to Arraylist
  12.         arrayList.add("a");
  13.         arrayList.add("b");
  14.         arrayList.add("c");
  15.         arrayList.add("d");
  16.         arrayList.add("f");
  17.         arrayList.add("g");
  18.  
  19.         arrayList.add(1,"Y");
  20.  
  21.         System.out.println("ArrayList values...");
  22.  
  23.         //display elements of ArrayList
  24.         for(int index=0; index < arrayList.size(); index++)
  25.           System.out.println(arrayList.get(index));
  26.        arrayList.add(2,"Z");
  27.  
  28.     System.out.println("ArrayList values...");
  29.  
  30.         //display elements of ArrayList
  31.        for(int index=0; index < arrayList.size(); index++)
  32.           System.out.println(arrayList.get(index));
  33.       }
  34.  
  35. }
  36. }
     

  1. OutPut:
  2. ArrayList values...
  3. a
  4. Y
  5. b
  6. c
  7. d
  8. f
  9. g
  10. ArrayList values...
  11. a
  12. Y
  13. Z
  14. b
  15. c
  16. d
  17. f
  18. g
     

String vs stringbuffer vs stringbuilder

1.Definition:

  • String is an immutable sequence of characters.
  • StringBuffer is mutable sequence of characters.
  • StringBuilder is also mutable sequence of characters.

The only difference between StringBuffer and StringBuilder: 

  • StringBuffer object is thread safe , it means StringBuffer object is modified by multiple concurrently, because  all its methods are declared as "synchronized".
  • StringBuilder class is given in jdk 1.5 version as non thread -safe class, means all its methods are non synchronized methods.
  • So , in single model application we must use StringBuilder, so that object locking and unlocking will not be there, hence performance is increased.
  • In single thread model application operations are executed in sequence hence there is no chance of object corruption.

When should we choose String and StringBuffer? 

  • If we do not want to store string modifications in the same memory we must choose String.
  • To do modifications in the same memory, we must choose StringBuffer or StringBuilder.

 Advantage and disadvantage in String: 

  • Advantage : Since modifications are preserving in another memory location, we will have both original and modified values.
  • Disadvantage: It consumes lot memory for every operation, as it stores it modifications in new memory. So it leads to performance issue.
  • Solution: To solve this performance issue , in projects developers store string data using StringBuilder or StringBuffer after all modifications they convert into String and pass it back to user.

Advantage and disadvantage of StringBuffer or StringBuilder:

  • Advantage: It given high performance because consumes less memory as all modifications stored in same memory.
  • Disadvantage: Original value will not be preserved.


2.Creating String , StringBuffer objects: 

String:

  • String object can be created in two ways.
  • By using string literal : String str="instance of java ";
  • By using its constructors: String str= new String("instaneofjavaforus") ;

StringBuffer:

  • By using its available constructors
  • StringBuffer str= new StringBuffer();

StringBuilder:

  • By using its available constructors
  • StringBuilder str= new StringBuilder ();

3.Special operations those we can only perform on StringBuffer and StringBuilder: 

  1. append
  2. insert
  3. delete
  4. reverse
  •  Since string is immutable we cannot perform these operations on String.

4.Concatenation:

  • Using String object we can concat new string to the current  string in two ways.
  1. Using + operator
  2. using concat() method.
  • Using StringBuffer we can perform concat operation only in one way
  1. Using append() method
  • Using StringBuilder we can perform concat operation only in one way
  1. Using append() method

  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.         String str="Java";
  7.         StringBuffer sb= new StringBuffer("Java");
  8.         StringBuilder sbr= new StringBuilder("Java");
  9.  
  10.        System.out.println(str.concat(" language"));    
  11.        System.out.println(sb.append(" language"));
  12.         System.out.println(sbr.append(" language"));
  13. }
  14. }
  15.  
  16. OutPut:
  17. Java language
  18. Java language
  19. Java language


5.Comparison:

  • Using equals() method String objects are compared with state, because it is overridden in this class. Also hashcode(0 method is overridden in order to satisfy equals() method contract.
  • But in StringBuffer and in StringBuilder equals() method is not overridden , so using equals() method their object are compared with reference. 
You might like:

StringBuffer class in java


  • StringBuffer is a thread safe, mutable sequence of characters.
  • A StringBuffer is like a String , but can be modified in the same memory location.
By using following constructors we can create StringBuffer class object.

Constructors;

1.public StringBuffer(): 

  • It  creates empty StringBuffer object with default capacity 16 characters, it means it holds 16 empty locations.
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer();
  7.   System.out.println(sb.capacity());
  8. }
  9. }
  10.  
  11. OutPut:
  12. 16


2.public StringBuffer(int capacity):

  • It creates StringBuffer object with given capacity.
  • Capacity value should be positive value. means >=0.
  • If we pass negative value JVM throws "java.lang.NegativeArraySizeException".

  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.  StringBuffer sb= new StringBuffer(12);
  7.  System.out.println(sb.capacity());
  8.  
  9. }
  10. }

  11. OutPut:
  12. 12

3.public StringBuffer(String s):

  • It creates StringBuffer object characters available in passed String object and with default capacity 16 (16+String length) .
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.  StringBuffer sb= new StringBuffer(new String("abc"));
  7.  System.out.println(sb.capacity());
  8.  
  9. }
  10. }

  11. OutPut:
  12. 19

4.public StringBuffer(charSequence s):

  •  It creates StringBuffer object characters available in passed charSequence object and with default capacity 16 (16+charSequence length) .
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.  CharSequence cs = "abc";
  7.  StringBuffer sb= new StringBuffer(cs);
  8.  System.out.println(sb.capacity());
  9.  
  10. }
  11. }

  12. OutPut:
  13. 19

Methods :

1.public StringBuffer append(XXX s);

  • append(String s) methods concatenates the given String and returns updated StringBuffer object. 
  • There are 8 methods with same name for accepting 8 primitive data type values.
  • And 3 more methods for accepting StringBuffer object , Object and String objects.
  1. public StringBuffer append(boolean b)
  2. public StringBuffer append(char c) 
  3. public StringBuffer append(char[] str) 
  4. public StringBuffer append(char[] str, int offset, int len) 
  5. public StringBuffer append(double d) 
  6. public StringBuffer append(float f)
  7. public StringBuffer append(int i) 
  8. public StringBuffer append(long l) 
  9. public StringBuffer append(Object obj) 
  10. public StringBuffer append(StringBuffer sb) 
  11. public StringBuffer append(String str) 

  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer();
  7.   sb.append("abc");
  8.   System.out.println(sb);
  9. }
  10. }
  11.  
  12. OutPut:
  13. abc

 

2.public StringBuffer insert(XXX s);

  • where xxx is java data types 
  • overloaded to take all possible java data type values
  1. public StringBuffer insert(int offset, boolean b)
  2. public StringBuffer insert(int offset, char c)
  3. public insert(int offset, char[] str)
  4. public StringBuffer insert(int index, char[] str, int offset, int len)
  5. public StringBuffer insert(int offset, float f)  
  6. public StringBuffer insert(int offset, int i)
  7. public StringBuffer insert(int offset, long l) 
  8. public StringBuffer insert(int offset, Object obj) 
  9. public StringBuffer insert(int offset, String str)

  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer("abc");
  7.    sb.insert(1, "c");
  8.   System.out.println(sb);
  9. }
  10. }
  11.  
  12. OutPut:
  13. acbc

 

3. public StringBuffer deleteCharAt(int index):

  • This method used to delete character at specified index.
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer("Java");
  7.    sb.deleteCharAt(1);
  8.   System.out.println(sb);
  9. }
  10. }
  11.  
  12. OutPut:
  13. Jva

 

4. public StringBuffer delete(int start , int end):

  • This method used to delete characters from specified start index to end index
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer("Java Language");
  7.    sb.delete(1,3);
  8.   System.out.println(sb);
  9. }
  10. }
  11.  
  12. OutPut:
  13. Ja Language

 

5. public StringBuffer setCharAt(int index, char ch):

  • This method used to insert character at specified index
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer("Java Language");
  7.       sb.insert(0, 'S');
  8.   System.out.println(sb);
  9. }
  10. }
  11.  
  12. OutPut:
  13. SJava Language



6. public int indexOf(String str):

  • This method returns index of specified sub string. if not found returns -1.
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer("Java Language");
  7.    System.out.println(sb.indexOf("J"));
  8. }
  9. }
  10.  
  11. OutPut:
  12. 0

7. public int indexOf(String str, int index):

  • This method returns index of specified sub string. if not found returns -1.
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer("Java Language");
  7.  System.out.println(sb.indexOf("a",4));
  8. }
  9. }
  10.  
  11. OutPut:
  12. 6

8. public int lastIndexOf(String str):

  • This method returns last occurrence of  of specified sub string index . if not found returns -1.
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer("Java Language");
  7.  System.out.println(sb.lastIndexOf("a"));
  8. }
  9. }
  10.  
  11. OutPut:
  12. 10

9. public int length():

  • This method returns length of StringBuffer.
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer("Java Language");
  7.  System.out.println(sb.length());
  8. }
  9.  
  10. OutPut:
  11. 13

10. public StringBuffer replace(int start, int end, String s):

  • This method replaces the characters from start index to end index with specified string.
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer("Java Language");
  7.      System.out.println(sb.replace(0,4,"Instance of java"));
  8. }
  9.  
  10. OutPut:
  11. Instance of java Language

11. public StringBuffer reverse():

  • This method returns reverse of sequence of characters.
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer("Java Language");
  7.        System.out.println(sb.reverse());
  8. }
  9.  
  10. OutPut:
  11. egaugnaL avaJ


12. public String subString(int start, int end):

  • This method returns sub string from start index to end index as a string.
  1. package com.instanceofjavaforus;
  2. public Class SBDemo{ 
  3.  
  4. public static void main (String args[]) {
  5.  
  6.   StringBuffer sb= new StringBuffer("Java Language");
  7.     System.out.println(sb.substring(1,3));
  8.  
  9. }
  10.  
  11. OutPut:
  12. av
Select Menu