Design Pattern Basic Tutorial

adplus-dvertising
Factory Method Pattern
Previous Home Next

The Factory Method pattern is used when the decision is take at the run time. the factory pattern take the decision which one of the several compatible classes is firstly instantiated. the factory pattern is used throughout the java Application programming interface. the factory pattern is very useful for the connect to the parallel class in hierarchies. the factory method pattern is provide the hook of the subclass which is more flexible than creating object directly.

Example

package r4r;
import java.util.*;
public class Employee {
public String name;
private String Id = "100";
public String getName() {
return name;
}
public String getId() {
return Id;
}
}
class Admin extends Employee {
public void Employee(String fullName) {
System.out.println("Hello Mr. "+ fullName + 
"You are the administrator of this organization");
}
}
class NotAnAdmin extends Person {
public void NotanAdmin(String fullNname) {
System.out.println("Hello Mr. " + fullNname + 
"you are not the administrator of this organization");
}

//class Person {
//public void NotanAdmin(String fullNname) {
//System.out.println("Hello Mr. " + fullNname +
//"you are not the administrator of this organization");
//}
//}


public class factorytests {
public static void main(String[] args) {
factorytests test = new factorytests();
test.getEmployee(args[0], args[1]);
}

public Employee getEmployee(String name, String Id) {
if ((name.equals("Zulfiqar"))&&(Id.equals("123542")))
return new Admin(name);
else
return new NotanAdmin(name);
}
}
}

package r4r;
public class Person {
public void NotanAdmin(String fullNname) {
System.out.println("Hello Mr. " + fullNname +
"you are not the administrator of this organization");
}
}
Previous Home Next