Java 对具有额外构造函数参数的子类使用factory设计模式
假设我有以下案例父类和两个子类,每个子类向从父类继承的参数添加一个新参数。范例Java 对具有额外构造函数参数的子类使用factory设计模式,java,design-patterns,factory,Java,Design Patterns,Factory,假设我有以下案例父类和两个子类,每个子类向从父类继承的参数添加一个新参数。范例 public class Parent { private int x; public Parent(int x) {this.x = x;} public int getX() {return x;} public void setX(int x) {this.x = x;} } 第一个孩子 public class FirstChild extends Parent { private int y;
public class Parent {
private int x;
public Parent(int x) {this.x = x;}
public int getX() {return x;}
public void setX(int x) {this.x = x;}
}
第一个孩子
public class FirstChild extends Parent {
private int y;
public FirstChild(int x, int y) {
super(x);
this.y = y;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
第二胎
public class SecondChild extends Parent{
private int z;
public SecondChild(int x, int z) {
super(x);
this.z = z;
}
public int getZ() {
return z;
}
public void setZ(int z) {
this.z = z;
}
}
那么我如何在这里使用工厂方法呢?您可能有一个工厂类,它生成第一个子级或第二个子级,如下所示
class Factory{
Parent createChild(String child) {
if(child.equals("first"))
return new FirstChild();
if(child.equals("second"))
return new SecondChild();
}
}
此外,下面的链接将帮助您更好地了解工厂模式
或者(可能更适合您的需要):
可能您真的不需要使用父接口。这里不能使用“纯”工厂或工厂方法模式。在创建实例的机制相似的情况下,如果您想要创建同一基类(或接口)的不同子类的实例,那么这些模式是很好的。例如,所有类都具有相同原型的构造函数或工厂方法
在这种情况下,可以使用反射或省略:
class MyFactory {
Parent createInstance(Class clazz, int ... args) {
if (FirstChild.class.equals(clazz)) {
return new FirstChild(args[0]);
}
if (SecondChild.class.equals(clazz)) {
return new SecondChild(args[0], args[1]);
}
throw new IllegalArgumentException(clazz.getName());
}
}
public class ChildrenFactory {
FirstChild newFistChild() { return new FirstChild(); }
SecondChild newSecondChild() { return new SecondChild(); }
// or
Parent newFistChild() { return new FirstChild(); }
Parent newSecondChild() { return new SecondChild(); }
}
class MyFactory {
Parent createInstance(Class clazz, int ... args) {
if (FirstChild.class.equals(clazz)) {
return new FirstChild(args[0]);
}
if (SecondChild.class.equals(clazz)) {
return new SecondChild(args[0], args[1]);
}
throw new IllegalArgumentException(clazz.getName());
}
}