我正在尝试用 Java 创建一个非常简单的工厂方法设计模式示例。我真的不了解 Java,我一般是编程新手,但我需要想出一个用 Java 实现的基本 FactoryMethod 示例。以下是我想出的。我敢肯定有很多错误,我显然缺少一些构造函数,并且我对抽象类和接口感到困惑。您能否指出我的错误并纠正我的代码以及解释?提前感谢您的时间和帮助。
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
}
}