X

Java Factory Design Pattern

This article talks about the factory design pattern in Java which is one of the popular design patterns used in Java.

Java is a very powerful language. Simplicity through object oriented programming creating more reliability and security are some of the major reasons why everyone is in love with it.

Factory design pattern is widely used in Java and considering its uses it rightfully earns the popularity. This method of design pattern is also known as virtual constructor.

When you are creating an object in Java, you may not know what types of objects you might need and where you might have to implement them. Factory design pattern tackles exactly this issue. You can understand a bit better by understanding the name of the design pattern itself. Consider a factory environment where different products are manufactured each day. The inventory contains all the materials required to manufacture the products but what type of products are being manufactured are not known before-hand.

In programming terms, you can compare the components in the inventory as classes but you will not know which of those to instantiate at run-time (what products to manufacture).

The term factory comes as the design pattern generates a lot of various types of objects without necessarily knowing what kind of object is created and how they are created. It is brought into use when we have a super class and various sub-classes.

Factory design pattern is considered as a creational design pattern and deployed in JDK and frameworks such as Spring and Struts.



Why use factory design pattern?

  • Allows the sub-classes to choose the type of objects to create during run-time
  • Promotes loose-coupling as it eliminates the need to bind application-specific classes into the code

When will you use the factory design pattern?

  • When you don’t know what sub-classes will be required by your classes
  • When you want your sub-classes to specify the objects to be generated

The super-class acts as a common interface or as an abstract class for creating objects but lets the subclasses decide which class to instantiate at run-time. So we can say that subclasses are responsible for creating an instance of the class.

 

Java Factory Design Pattern Example

Let us see an example of how the factory design pattern is implemented by taking a real world example and coding it.

Example of Factory design pattern

Step 1: Creating an abstract class called Courses

abstract class Courses{  
         protected int duration;  
         protected double fee;
         abstract void getDuration();  
         abstract void getFeePerSemester();  
   
         public void calculateTotalFee(){  
              System.out.println(duration*fee);  
          }  
}//end of Course class

Step 2: Creating the classes that extends Courses abstract class, here three courses are available which are Computer, Civil services and Health

class  Computer extends Courses{  
        //@override  
        public void getDuration(){  
             duration=8;             // duration in semesters            
        }  

        public void getFeePerSemester(){
	fee = 3000;             // fee in dollars   
        }
   }//end of Computer class.  

class  CivilServices extends Courses{  
        //@override  
         public void getDuration(){  
             duration=6;             // duration in semesters            
        }  

        public void getFeePerSemester(){
	fee = 2000;             // fee in dollars   
        }
}//end of CivilServices class.  


class  Health extends Courses{  
        //@override  
        public void getDuration(){  
             duration=10;             // duration in semesters            
        }  

        public void getFeePerSemester(){
	fee = 5000;             // fee in dollars   
        }
   }//end of Health class.

Step 3: Create an Admission class to generate object of sub-classes

class Admission{  
      
   //use admittingCourse method to get object of type Course   
       public Course admittingCourse (String courseName){  
           if(courseName == null){  
               return null;  
           }  
           if(courseName.equalsIgnoreCase("Computer")) {  
                 return new Computer();  
           }   
           else if(courseName.equalsIgnoreCase("CivilServices")){  
                return new CivilServices();  
           }   
           else if(courseName.equalsIgnoreCase("Health")) {  
                return new Health();  
           }  
      return null;  
   }  
}//end of Admission class.

Step 4: Generate information about the duration and fee of the course by using the Admission class to get the object of sub-classes by passing the required information like the course being applied for, namely Computer, Civil Services and Health.

import java.io.*;

class CourseInformation {
    public static void main(String args[]) throws IOException {
        Admission newApplication = new Admission();

        System.out.print("Enter the course you are trying to admit in: ");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String cousreName = br.readLine();

        Course c = newApplication.admittingCourse(courseName);

        System.out.print("For  " + courseName + "  the required duration you would have to study is: ");
        c.getDuration();
        System.out.print("For  " + courseName + "  the required fee you would have to pay per semester is: ");
        c.getFeePerSemester();
        System.out.print("The total amount you will have to pay for the entire course duration is:”);     
        c.calculateTotalFee();
    }
} //end of CourseInformation class.

 

This was a source code of a real world application of the factory design pattern in Java. Now you know what factory design pattern is, when you should use it and what the advantages of using it are.

 

0 0 votes
Article Rating
filip:

View Comments (1)

Related Post