Factory Method Pattern Example in Java troubles
design-patterns, factory, java
Solution
In brief there are several issues in your version that were corrected below:
- `createPerson` method is useless.
- The way you invoke the factory method is wrong.
- You use `==` instead of `.equals` in your factory method.
I've enhanced your Person class to add a member field that is shared by the Male and Female class, to demonstrate how sharing a common abstract constructor could be used.
public abstract class Person {
protected final String name;
public Person(String name) {
this.name = name;
}
}
public class Male extends Person {
public Male(String name) {
super(name);
}
}
public class Female extends Person {
public Female(String name) {
super(name);
}
}
public class PersonFactory
{
public static Person makePerson(String gender, String name)
{
if(gender.equals("male"))
{
Male man=new Male(name);
return man;
}
else
{
Female woman=new Female(name);
return woman;
}
}
}
public class Test
{
public static void main(String[] args)
{
Person y= PersonFactory.makePerson("male", "bob"));
Person z= new PersonFactory.makePerson("female", "janet"));
}
}
Problem
I'm trying to create a really simple Factory Method design pattern example in Java. I don't really know Java, I am new to programming in general but I need to come up with a a basic FactoryMethod example implemented in java. The following is what I came up with. There are quite a few errors I'm sure, I'm missing some constructors apparently and I get confused with abstract classes and interfaces. Could you point out my mistakes and correct my code along with an explanation please? Thank you in advance for your time and help. ``` public abstract class Person { public void createPerson(){ } } public class Male extends Person { @Override public void createPerson() { System.out.print("a man has been created"); } } public class Female extends Person { @Override public void createPerson() { System.out.print("a woman has been created"); } } public class PersonFactory { public static Person makePerson(String x) // I have no Person constructor in { // the actual abstract person class so if(x=="male") // is this valid here? { Male man=new Male(); return man; } else { Female woman=new Female(); return woman; } } } public class Test { public static void main(String[] args) { Person y= new Person(makePerson("male")); // definitely doing smth wrong here Person z= new Person(makePerson("female")); // yup, here as well } } ```