gpt4 book ai didi

java - 使用单个基类接口(interface)处理子类中的不同参数类型

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:36:05 24 4
gpt4 key购买 nike

我有一个工厂,可以让你创造一些不同类型的东西。每个事物的值(value)来自不同的来源,并且具有不同的类型。我希望类使用者使用单个 getValue() 和 setValue() 接口(interface),以便在基类中完成一些重要工作。我也想要子类能够处理一些不同的参数类型。目前,我正在做一些类型识别 jiggery-pokery(参见 Thing2)来处理不同的类型。有更好的方法吗?

我的问题:我在这里做的事情是否正确?

abstract class Thing {

public static Thing thingFactoryCreationary(byte iClass) {
// let's assume this is more sophisticated in real life.
return iClass==1 ? new Thing1() : new Thing2();
}

final public Object getValue() {
myImportantWorkFunction();
return _getValue();
}

final public void setValue(Object oValue) {
myImportantWorkFunction();
_setValue(oValue);
}

private void myImportantWorkFunction() {
// save the world here.
}

abstract protected Object _getValue();
abstract protected void _setValue(Object oValue);
}

class Thing1 extends Thing {
private String msMyStringPropertyValue;
protected String _getValue() {
return msMyStringPropertyValue;
}
protected void _setValue(Object oValue) {
msMyStringPropertyValue = oValue.toString();
}
}

class Thing2 extends Thing {

protected InputStream _getValue() {
return new FileInputStream("/some/file/descriptor");
}

protected void _setValue(Object oValue) {
InputStream oInStream = null;
if (InputStream.class.isInstance(oValue)) {
oInStream =(InputStream)oValue;
} else {
if (File.class.isInstance(oValue)) {
oInStream = new FileInputStream((File)oValue);
} else {
oInStream = new ByteArrayInputStream(oValue.toString().getBytes("UTF-8"));
}
}
FileOutputStream oOutStream = new FileOutputStream("/some/file/descriptor");
myFileStreamCopyFunction(oInStream, oOutStream);
}

private void myFileStreamCopyFunction(InputStream oInStream, OutputStream oOutStream) {
// reading and writing is fundamental.
}

}

谢谢。

最佳答案

是的,这是个好方法。也许你可以用泛型指定接受的类型:

public abstract class Thing<S, G> {
private G value;
public void setValue(S object);
public G getValue();
}
public class Thing1 extends Thing<String, String> {..}
public class Thing2 extends Thing<ResourceHolder, String> {..}

ResourceHolder 是一个简单的 bean,带有 InputStreamFile 的 getter 和 setter。 SG 分别代表 setter 和 getter - 你指定你期望设置什么,以及客户端调用 get 时期望什么

因此每个子类只能处理一种类型的值,但该类型可以包含多个选项。这样,您将使用简单的 null 检查而不是反射。

关于java - 使用单个基类接口(interface)处理子类中的不同参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7693758/

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