How to deal with multiple threads in one class?

后端 未结 6 1264
醉酒成梦
醉酒成梦 2021-02-04 12:31

Threads are often designed in two ways (see java tutorials): either by extending the Thread class or by implementing the Runnable class. Either way, you need to specify what wil

6条回答
  •  说谎
    说谎 (楼主)
    2021-02-04 13:08

    I don't see why you don't like the idea of creating multiple classes, considering Java doesn't support higher-order functions and the changeable part of your code is the algorithm.

    But if you wanted a single implementation of OnlineResourceAdapter you could use the Strategy pattern and do something like this:

    public interface InformationGetter {
      public void getInformation();
    }
    
    public class OnlineResourceAdapter implements Runnable {
      private final InformationGetter informationGetter;
    
      public OnlineResourceAdapter(InformationGetter i) {
        this.informationGetter = i;
      }
    
      public void run() {
          //get stuff from resource
          i.getInformation();
      }
    }
    

    and then of course you would create as many implementations of InformationGetter as you needed.

    Come to think about it, looking back over this approach, OnlineResourceAdapter now doesn't really add anything except making InformationGetter runnable. So unless you have some compelling reason not to, I would say just have InformationGetter implement Runnable directly.

提交回复
热议问题