gpt4 book ai didi

java - Java对象工厂可以用作构造函数吗?

转载 作者:行者123 更新时间:2023-11-30 05:58:37 24 4
gpt4 key购买 nike

我对 Java 还很陌生,所以希望这个问题不太愚蠢。

根据 Java 文档:“对象工厂是对象的生产者。它接受一些有关如何创建对象的信息,例如引用,然后返回该对象的实例。”

该实例如何成为构造函数的结果?

这里有一些(完全没有意义的)示例代码,说明了我正在尝试构建的类层次结构(使用简单的整数参数(如“1 2 3”来调用它)将明白这一点):

package number;

public class Factory {
public static void main(String[] args) {
for (String arg : args) {
// This is how I want to instantiate and use the Outer class:
Outer outer = new Outer(arg);
// But I don't know how to create Outer from the factory, and the results are wrong:
System.out.println("yields: " + outer.value + ", class: " + outer.Class());
// This is a workaround (that I can't use) that gives the correct results:
Number number = outer.Workaround(arg);
System.out.println("yields: " + number.value + ", class " + number.Class());
}
}
}

class Outer extends Inner {
Outer(String arg) {
super(arg);
}
}

class Inner extends Number {
Inner(String arg) {
// I don't want to do this:
super(arg);
// I want some way of doing this:
// return NumberFactory.getNumber(arg);
}
// Workaround method that I can't really use:
Number Workaround(String arg) {
return NumberFactory.getNumber(arg);
}
}

class NumberFactory {
static Number getNumber(String selection) {
switch (selection) {
case "1": return new First(selection);
case "2": return new Second(selection);
default: return new Other(selection);
}
}
}

class First extends Number {
First(String arg) { super(arg); value = "first"; }
String Class() { return "First"; }
}

class Second extends Number {
Second(String arg) { super(arg); value = "second"; }
String Class() { return "Second"; }
}

class Other extends Number {
Other(String arg) { super(arg); value = "other"; }
String Class() { return "Other"; }
}

class Number {
String arg;
String value = "default";
Number(String arg) {
this.arg = arg;
System.out.print("Number(" + arg + "), ");
}
String Class() { return "Number"; }
}

最佳答案

请解释一下您要做什么。

但这是我尝试回答你的问题。

创建新的 Java 对象时会使用构造函数。当您使用 new SomeObject() 编译器使用构造函数

SomeObject(){ 
// some logic here
}

使用 SomeObject.class 创建对象。对象在其生命周期中如何创建和维护取决于 JVM。您可以在这里找到更多信息。 https://en.wikibooks.org/wiki/Java_Programming/Object_Lifecycle

对象工厂也用于创建对象,但反过来它们使用对象构造函数来实例化其中的对象(正如您已经这样做的那样)。对象工厂用于将对象创建的逻辑委托(delegate)给一个中心位置,以便代码不重复且组织良好。在此处了解有关对象工厂的更多信息 https://github.com/iluwatar/java-design-patterns/tree/master/abstract-factory

另一件事是你不必在你实现的每个类中实现String Class()方法。 SomeObject.class.toString() 将为您完成。

关于java - Java对象工厂可以用作构造函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52675193/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com