3
我有一个工厂,可以让您创建一些不同类型的东西。每件事物的价值来自不同的来源,并且具有不同的类型。 我希望类消费者使用单个getValue()和setValue()接口来完成基类中的一些重要工作。我也希望子类 能够处理几个不同的参数类型。目前,我正在做一些类型识别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.
}
}
谢谢。
我喜欢资源持有人模板类的想法。它只是让事情变得更加清洁,尽管我仍然必须确保我的子类获得正确的资源,但它会感觉更干净。非常感谢! – MoatMonster