5 java design-patterns factory
我正在尝试用Java创建一个非常简单的Factory Method设计模式示例.我真的不懂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
}
}
Run Code Online (Sandbox Code Playgroud)
简而言之,您的版本中有几个问题已在下面更正:
createPerson 方法没用.==而不是.equals在工厂方法中.我已经增强了你的Person类,以添加一个由Male和Female类共享的成员字段,以演示如何使用共享的常见抽象构造函数.
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"));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11603 次 |
| 最近记录: |