我有7-8个可调用的类,它利用了一些类似的功能,还读取了一些相同的列表和HashMap。因此,我创建了一个静态类,其中包含静态函数、静态列表和hashMap等所有功能。
现在,我有一些疑问:
1.)在java中使用静态类是一种错误的做法吗?因为我的前辈责备我使用静态类,并要求我将其转换为单例类。
但是静态类比单例更快。不是吗?
2.)引用静态/非静态方法来获取一些数据,比如调用方法(在线程中)中的列表,或者执行一些任务,这是一个糟糕的设计吗?
它是否像我的前辈所说的那样违反了线程安全性或并行性?并要求我将列表作为私有成员放在线程类中。
但这并不是很糟糕的内存使用,因为其他6-7线程类使用相同的列表进行只读。
3.)我如何在提高性能的同时改进面向对象的设计。
示例代码将如下所示:
public class StaticClass {
private static List<String> ListOne;
private static List<String> listTwo;
private static HashMap<String, String> hMap;
static{
//initialize list and maps by reading from file
}
public static List<String> getListOne() {
return ListOne;
}
public static List<String> getListTwo() {
return listTwo;
}
public static HashMap<String, String> gethMap() {
return hMap;
}
public static void commonMethodOne(){
}
public static String commonMethodTwo(){
}
public static String[] commonMethodThree(){
}
}
public class CallableThread implements Callable<String>{
public String call(){
HashMap<String, String> mapTask = StaticClass.gethMap();
List<String> taskOne =StaticClass.getListOne();
for(String temp : taskOne){
//do what you are suppose to do
}
for(String key : mapTask.keySet()){
//do what you are supposed to do
}
return "Done with CallableThread";
}
}发布于 2015-09-06 00:13:25
像这样的方法是一个糟糕的想法(糟糕的命名和未能遵循Java编码标准):
public static List<String> getListOne() {
return ListOne;
}您返回一个可变的引用,因此任何获得此列表的人都可以根据自己的需要修改它的内容。private不再是Private。
如果您必须返回对私有列表或数据结构的引用(据我所知,没有理由这样做),则应该使其不可变或返回一个副本。
public static List<String> getListOne() {
return Collections.unmodifiableList(ListOne);
}你得到了可变的共享数据,没有任何类型的同步,所以这个类根本不是线程安全的。
发布于 2015-09-06 01:37:54
我认为单例比静态类要好得多。
以下是对你的问题的连续回答:
1)不,这完全取决于您的需求,但静态类更快,但也允许在您的项目中出现更多错误
2)是的,有时只要不影响您的私人数据成员,并使您的数据不安全
3)使用单例,因为它提供了更多的OO功能,从而提高了性能
这是一篇很好的参考文章:
http://javarevisited.blogspot.in/2013/03/difference-between-singleton-pattern-vs-static-class-java.html
https://stackoverflow.com/questions/32415066
复制相似问题