Factory Design Pattern in Java

May 1 201022 Commented

Categorized Under: Java

If you are a novice or experienced java programmer, design pattern is something you should have in your arsenal. This is important if you are going to attend an interview or developing an enterprise level application. One of the most important thing about design pattern is apply the right pattern at right place.

Let us examine a practical scenario which is suitable for factory pattern.

We are developing an enterprise application. You are responsible for authentication module. But you are not sure how you are going to do authentication. You can have authentication against LDAP, database or any other centralized directory. So you first define an interface for authentication with single method authorize() This method returns true if user is successfully authenticated or false if not authenticated.

public interface UserAuthentication {
 
	public boolean authorize();	
 
}

OK, now let us create concreate implementation for this interface. Since you can have multiple ways of authenticating against users, you would like to create multiple derived classes.

Let us create a class which authenticate against users table in database using JDBC.

public class JDBCUserAuthentication implements UserAuthentication {
 
	@Override
	public boolean authorize() {
		boolean result=false;
		// implementation for authentication using JDBC
		//if authenticated
		//result=true
		//else
		//result=false
		return result;
	}
 
}

Similarly another class which authenticate against LDAP.

public class LDAPUserAuthentication implements UserAuthentication {
 
	@Override
	public boolean authorize() {
		boolean result=false;
		// implementation for authentication using LDAP
		//if authenticated
		//result=true
		//else
		//result=false
		return result;
	}
 
}

Well, now we have two implementations, one using JDBC and another using LDAP. Now let us create factory class.

public class UserAuthenticationFactory {
 
	public static UserAuthentication getUserAuthentication(String type){
 
		if (type.equalsIgnoreCase("jdbc")){
			return new JDBCUserAuthentication();
		}else if(type.equalsIgnoreCase("ldap")){
			return new LDAPUserAuthentication();
		}else{
			return new JDBCUserAuthentication();
		}
	}
 
}

In the above class we define a static method getUserAuthentication() which instantiates appropriate sub class based on parameter.

When you do authentication your code snippet may be as follows.

//declare isAuthorized variable
boolean isAuthorized=false;
//get UserAuthentication object
UserAuthentication userAuthentication=
	UserAuthenticationFactory.getUserAuthentication("jdbc");
 
isAuthorized=userAuthentication.authorize();
if(isAuthorized){
	//redirect to home page
}else{
	//redirect to login page
}

Here we call static method of our factory class which in turn instantiates JDBCUserAuthentication class because we pass parameter as as “jdbc”. But the user who write client call for authentication do not require to know which derived class is instantiated and its implementation details.

I hope you got enough clarity about factory method pattern and its implementation in practical scenario.

cheers,

22 Responses to “Factory Design Pattern in Java”

  1. Vlado says:

    I believe this is more the classical factory pattern, not factory method pattern.

  2. Pintu Das says:

    The above is Simple Factory pattern not Factory Method pattern.
    So be careful.

  3. Balaguru says:

    Great.. Easy to understand. You had given a very good practical example and explained in much better way to make me understand. Hats off.

  4. vikas says:

    Nice example:)

  5. SHAILESH says:

    GOOD ARTICLE …….. THANKS

  6. Vijay says:

    more understandable and easy

  7. Sodb says:

    Here another example:

    public class MammalsFactory {
    public static Mammals getMammalObject(String name) {
    if (name.equalsIgnoreCase(“Cat”)){
    return new Cat();
    } else {
    return new Dog();
    }
    }
    }

    public abstract class Mammals {
    public abstract String doWalking();
    }

    public class Dog extends Mammals {
    public String doWalking() {
    return “Dogs has been Informed to perform Walk Operation”;
    }
    }

    public class Cat extends Mammals {
    public String doWalking() {
    return “Cats has been Informed to perform Walk Operation”;
    }
    }

    ————-main————-

    public class FactoryClient {
    public static void main(String args[]) {
    MammalsFactory mf = new MammalsFactory();
    System.out.println(mf.getMammalObject(“Dog”).doWalking());
    }
    }

  8. srinivas says:

    After googling some many websites,finally i got gud site which clearly explains design patterns concept.if u mention advantages and disavantages of design pattern it will be very nice.anyway thnx a lot.keeep it up gud work

  9. Dileep Maurya says:

    I am writing comment first time for any article.Its very simple and to the point.
    Thanks for writing so simple codes kindly write more articles on java

  10. chakri says:

    thnx a lot…explanation is so simple,clear and to the point.

  11. Nayan says:

    Browsed through n number of sites through the web, didnt find a single site which would, show me why we use the factory method pattern and how.
    This is just perfect i what i can say.

  12. padma naresh says:

    wow…. simply understandable……thank u very much

  13. Srinivas says:

    It took 2 long years to find a nice website where I can find design patterns illustrated like this. and there is no way you can find a better explanation than this.

  14. Devesh says:

    Hi,

    I really loved your site. Your explanation is absolutely clear. Could it be possible for you to explain some more design pattern such as (Session Facade, Observer etc).

    That will be really great help for all of us.

    Keep the momentum and go ahead with good work.

    Thanks,
    Devesh

  15. Andy says:

    finaly i understood practically

  16. Pankaj says:

    WOW!! I looked into other websites ..but you are the best among them!! GO AHEAD!

  17. Tarun says:

    Very simple and easy article to grasp. Thank you very much !!

  18. jmk says:

    very nice easy to understand thnX!

  19. RajHasthi says:

    Excellent and simple way of explaining..Thanks

  20. sireesha says:

    simple and excellent article

  21. Seji Thomas says:

    Wah!!! finally ur plans are Live.

    Let this seedling grow in to big tree and yield flowers and fruits. All the best.

Leave a Reply

*