Searching...
Saturday, 17 May 2014

Factory Method Pattern Example

05:28

Factory method pattern is one of the important Creational design pattern in java. Factory will create instance of classes based on the input and return to the user. Here is one simple example to create factory and create objects based on the logic.

image

1. Create an Interface (Person.java)

package com.pretech.design.factory;
public interface Person {
	void say();
	
}

2. Create Implementation classes (Male.java and Female.java)

package com.pretech.design.factory;
public class Male implements Person {
	public void say() {
		System.out.println("I am male");
	}
}

3. Create Factory class

package com.pretech.design.factory;
public class PersonFactory {
	public Person gePerson(String gender) {
		Person p = null;
		if (gender.equals("M")) {
			p = new Male();
		}
		if (gender.equals("F")) {
			p = new Female();
		}
		return p;
	}
}

4. Create a main class to use Factory

package com.pretech.design.factory;
public class FactoryTest {
	public static void main(String[] args) {
		PersonFactory factory = new PersonFactory();
		Person p = factory.gePerson("M");
		p.say();
	}
}

Output



I am male


0 comments: