nullobject for Java中的File [英] nullobject for File in Java
问题描述
我有一个类,偶尔会被 null
为文件
对象传递。在正常操作期间,它使用 Scanner
类来解析文件。
而不是用 null
检查文件
对象,我以为我可以替换文件
但是,它看起来像文件
不是真正设计的被延长有没有任何指针有关如何做到这一点?
您可以将使用该文件的对象替换为NullObject
例如,您可以使用NullInputStream并将其传递给扫描仪。
之前:
public void whatever(File f){
扫描仪扫描仪=新扫描仪(f);
...
}
之后
public void whatever(File f){
扫描仪扫描仪= new Scanner(getInputStreamFrom(f));
...
}
喜欢:
私有final InputStream getInputStreamFrom(File f){
if(f == null& ;&!f.exists()){
return NullInputStream.instance;
}
返回新的InputStream(new FileInputStream(f));
}
class NulllInputStream扩展InputStream {
private final static NullInputStream instance = new NullInputStream();
private NullInputStream(){
}
public int read(){
return -1;
}
....其他相关方法在这里...
}
显然编码仔细,不在3分钟内。因为我:) :) :)
I have a class that occasionally gets passed null
for File
objects. During normal operation it uses a Scanner
class to parse through the file.
Instead of littering my code with null
checks against the File
objects, I thought I could replace the File
s with nullobjects (Gang of Four style).
However, it looks like File
isn't really designed to be extended. Does any one have any pointers on how to do this?
You can replace the object that uses the file with a NullObject
For instance, you can use a NullInputStream and pass it to the scanner.
Before:
public void whatever( File f ) {
Scanner scanner = new Scanner( f );
...
}
After
public void whatever( File f ) {
Scanner scanner = new Scanner( getInputStreamFrom( f ) );
...
}
And have that method implemented like:
private final InputStream getInputStreamFrom( File f ) {
if( f == null && !f.exists() ) {
return NullInputStream.instance;
}
return new InputStream( new FileInputStream( f ) );
}
class NulllInputStream extends InputStream {
private final static NullInputStream instance = new NullInputStream();
private NullInputStream() {
}
public int read() {
return -1;
}
.... other relevant methods here...
}
Obviously coded carefully and not in 3 mins. as I did :) :) :)
这篇关于nullobject for Java中的File的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!