Example of factory pattern in java

1. Introduction
2. Example in java

The factory pattern is the most common pattern in object oriented programs. A Factory pattern is one that returns an instance of one of several possible classes depending on the data provided to it. Usually all of the classes it returns have a common parent class and common methods, but each of them performs a task differently and is optimized for different kinds of data.

Example in java
Here, A program for detecting first and last name according with given full name. First and last name should be separated with “,”[comma] in given full name.

Class for storing first and last name

class Namer {

    protected String last;
    protected String first;

    public String getFirst() {
        return first;

    public String getLast() {
        return last;

Class for detecting first name if given name contains only first name

class FirstFirst extends Namer {

    public FirstFirst(String s) {
        int i = s.lastIndexOf(" ");
        if (i > 0) {
            first = s.substring(0, i).trim();
            last = s.substring(i + 1).trim();
        } else {
            first = "";
            last = s;


Class for detecting last and first name

class LastFirst extends Namer {

    public LastFirst(String s) {
        int i = s.indexOf(",");
        if (i > 0) {
            last = s.substring(0, i).trim();
            first = s.substring(i + 1).trim();
        } else {
            last = s;
            first = "";


Building the factory
Now our factory class is extremely simple. We just test for the existence of a comma and then return an instance of one class or the other:

class NameFactory {

    public Namer getNamer(String entry) {
        int i = entry.indexOf(",");

        if (i > 0) {
            return new  LastFirst(entry);
        } else {
            return new FirstFirst(entry);


Now using factory class

public class Main {
    private static Namer namer;

     * @param args the command line arguments
    private static NameFactory nfactory = new NameFactory();
    public static void main(String[] args) {
        String text="islam, shaiful";
        namer = nfactory.getNamer(text);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s