【问题标题】:OO design vs static classes in java and concurrency exploitationOO设计与Java中的静态类和并发利用
【发布时间】:2015-09-05 16:02:09
【问题描述】:

我有 7-8 个可调用的类,它们利用了一些类似的功能,并且还读取了一些相同的列表和 HashMap。 所以我创建了一个静态类,其中包含静态函数、静态列表和 hashMap 等所有功能。

现在,我有一些疑问:

1.) 在 java 中使用静态类是错误的做法吗,因为我的学长责备我使用静态类并要求我将其转换为单例类。

但是静态类比单例更快。不是吗?

2.) 引用静态/非静态方法来获取一些数据,如调用方法(在线程中)内的列表或执行某些任务,这是一个糟糕的设计吗?

它是否违反了我的学长所说的线程安全或并行性?并要求我将线程类中的列表作为私有成员。

但是内存使用不是很糟糕,因为其他 6-7 线程类使用相同的列表进行只读。

3.) 如何在提高性能的同时改进 OO 设计。

示例代码如下所示:

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";
    }
}

【问题讨论】:

  • 没有“资深”人士会推荐单身人士。我认为制作这个静态或单例没有任何好处。如果您有可变的共享数据,则最好注意正确同步它。在我看来,您担心的是错误的事情。

标签: java multithreading oop concurrency


【解决方案1】:

这样的方法是一个糟糕的想法(命名不佳和未能遵循 Java 编码标准):

public static List<String> getListOne() {
    return ListOne;
}

您返回一个可变引用,因此任何获得此列表的人都可以根据需要修改其内容。私人不再是私人的。

如果您必须返回对私有列表或数据结构的引用(我可以看到没有理由这样做),您应该使其不可变或返回一个副本。

public static List<String> getListOne() {
    return Collections.unmodifiableList(ListOne);
}

你有没有任何同步的可变共享数据,所以这个类根本不是线程安全的。

【讨论】:

    【解决方案2】:

    我认为单例比静态类要好得多

    以下是对您问题的连续回答:

    1) 不,这完全取决于您的要求,但是静态类更快,但也允许更多错误进入您的项目

    2) 有时是的,只要它不影响您的私人数据成员并使您的数据不安全

    3) 使用单例,因为它提供了更多的 OO 功能,从而提高了性能

    这是一篇很棒的参考文章:

    http://javarevisited.blogspot.in/2013/03/difference-between-singleton-pattern-vs-static-class-java.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-03
      相关资源
      最近更新 更多