Factory Design Pattern is probably the most used design pattern in Java programming. It is a Creational Design Pattern like Singleton and hence used for creating objects.
To be continued...
This blog will have tutorials of development of Java/J2EE application from scratch so that it could be of a great help to newbies. There will also be many tutorials and articles about Design Patterns, Spring Framework, Hibernate ORM, Java 7/8, Angular Js, Java-XML and Interview Questions for Java Developers.
package com.bpjoshi.singleton; public class Employee { //Make an Instance of Singleton class private static final Employee instance = new Employee(); //make its constructor private private Employee(){} //Make a getInstance() method to retrieve the singleton public static Employee getInstance(){ return instance; } }
package com.bpjoshi.singleton; public class Employee { //Declare Instance of Singleton class private static final Employee instance; //make its constructor private private Employee(){} //Make a getInstance() method to retrieve the singleton public static Employee getInstance(){ if(instance==null){ instance= new Employee(); } return instance; } }
package com.bpjoshi.singleton; public class Employee { //Declare Instance of Singleton class private static final Employee instance; //make its constructor private private Employee(){} //Make a getInstance() method to retrieve the singleton public static synchronized Employee getInstance(){ if(instance==null){ instance= new Employee(); } return instance; } }
package com.bpjoshi.singleton;
public class Employee {
//private constructor of employee
private Employee(){}
//private static inner helper class
private static class EmployeeHelper{
private static final Employee instance
=new Employee();
}
//public method to get singleton object
public static Employee getInstance(){
return EmployeeHelper.instance;
}
}
package com.bpjoshi.singleton; import java.lang.reflect.*; public class EmployeeReflection { public static void main(String[] args) { Employee instance1 = Employee.getInstance(); Employee instance2 = null; try { Constructor[] cstr = Employee.class.getDeclaredConstructors(); for (Constructor constructor : cstr) { //Setting constructor accessible constructor.setAccessible(true); instance2 = (Employee) constructor.newInstance(); break; } } catch (Exception e) { System.out.println(e); } System.out.println(instance1); System.out.println(instance2); } }
public enum Employee{ INSTANCE; }
public class Employee implements Serializable { //some code here //call this method immediately after De-serialization //it returns an instance of singleton protected Object readResolve() { return getInstance(); } }