java这个文件操作设计模式的名称是什么?
假设我有一个用于路径对象的包装器类,我想存储一些其他信息:例如哈希代码和文件类型
public class FileWrapperClass {
private Path thePath;
private String hashCode;
private String fileType;
...
public void setPathFromUserInput(JFrame whatever) { ... }
public void generateHashCode() { ... }
public boolean testHashCodeAgainst(Path testAgainstMe) { ... }
public void determineFileType() { ... }
...
public Path getPath() { return thePath; }
public void setPath(Path thePath) { this.thePath = thePath; }
public String getHashCode() { return hashCode; }
public String getFileType() { return fileType; }
}
generateHashCode()、TestHashCodeCountry(Path)和determineFileType()的逻辑不必包含在此FileWrapperClass中,如果这些FileWrapperClass对象可能有数百万个,则可能不应该包含这些逻辑
所以,我突然想到,我可能会把它拉到另一个类中,使它们成为在FileWrapperClass实例上操作的静态方法。这让我可以抽出除最基本的getter和setter之外的所有getter和setter,如下所示:
public class FileWrapperClass {
private Path thePath;
private String hashCode;
private String fileType;
...
public Path getPath() { return thePath; }
public void setPath(Path thePath) { this.thePath = thePath; }
public String getHashCode() { return hashCode; }
public void setHashCode(String hashCode) { this.hashCode = hashCode; }
public String getFileType() { return fileType; }
public String setFileType(String fileType) { this.fileType = fileType; }
}
public class FileWrapperClassOperator {
public static void setPathFromUserInput(JFrame whatever) { ... }
public static void generateHashCode() { ... }
public static boolean testHashCodeAgainst(Path testAgainstMe) { ... }
public static void determineFileType() { ... }
}
事实上,如果取消整个getter/setter动态而使用直接访问保护变量(尽管违反了OO原则,但性能提高值得吗?),难道不会产生更好的性能吗,比如:
public class FileWrapperClass {
public Path thePath;
public String hashCode;
public String fileType;
...
}
public class FileWrapperClassOperator {
public static void setPathFromUserInput(JFrame whatever) { ... }
public static void generateHashCode() { ... }
public static boolean testHashCodeAgainst(Path testAgainstMe) { ... }
public static void determineFileType() { ... }
}
我觉得我对这里有些了解。如果它是一个现有的设计模式,那么我想知道它是什么,以便我可以学习它并编写代码。如果没有,那么任务就是优化这个概念
需要明确的是,hashCode和fileType是任意数据段。我试图从被实例化数百万次的类中删除尽可能多的代码,并将其放入另一个单例类中,该类包含一组静态方法,这些方法对被实例化数百万次的类的实例进行操作。 这个设计模式有名字吗? 谢谢
# 1 楼答案
我认为你的“模式”是基于一些误解
你认为这数百万个实例中的每一个都包含了代码吗?如果是,那么您就错了,代码是共享的,创建单独的静态方法来处理它们没有任何好处
不,这里不涉及性能增益。这是一种微优化,JIT无论如何都会使其变得不必要
作为结论,对不起,你还没有“找到什么”,但我希望你现在“走上了正确的道路”
# 2 楼答案
对我来说,这听起来像是Anemic Domain Model和Premature Optimization之间的组合