假设我有一个用于Path对象的包装类,我想要存储有关它的一些其他信息: hashCode和fileType。
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()、testHashCodeAgainst(Path)和determineFileType()的逻辑不一定要包含在这个FileWrapperClass中,如果可能有数百万个这样的FileWrapperClass对象,可能也不应该包含。
所以,我突然想到,我可以把它拉到另一个类中,使它们成为在FileWrapperClass实例上操作的静态方法。这使我可以提取除最基本的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动态而支持直接访问保护变量,不会产生更好的性能吗(尽管违反了面向对象原则。为了提高性能,这样做值得吗?),比如:
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是任意的数据片段。我正在尝试从被实例化数百万次的类中删除尽可能多的代码,并将其放入另一个具有一堆静态方法的单一类中,这些方法对被实例化数百万次的类的实例进行操作。这个设计模式有名字吗?谢谢
发布于 2014-01-29 21:40:30
对我来说,这听起来像是Anemic Domain Model和Premature Optimization的结合。
https://stackoverflow.com/questions/21432365
复制相似问题