How to choose in runtime among several OSGi services in an intelligent way?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-03 07:23:42

This looks to me like a strategy pattern, which can very well be implemented using services. Assuming you have a type of service called Operator (and have an interface with the same name), this would work roughly like this:

  • Create a OperatorProvider service, which contains the necessary functionality, and some additional information (such as, when is this implementation suitable), and create a number of instances of that, one for each of your strategies.
  • Create a selector service, which implements the Operator interface, and channels all calls to the service to the most suitable OperatorProvider. The way in which this service selects the most suitable provider, is probably part of the intelligence.
  • The actual user of the service now only has a dependency on an Operator service, and does not have to worry about the provider selection.

I assume you can put the selection strategy in the selector service, but if it really is an external component, you can use any mechanism you like to handle the communication between the intelligent component and the selector: a service interface, events, etc.

I guess, some sort of dynamic strategy pattern or even dependency injection could fit your needs. Some class uses a strategy (you called it operator) which can change at runtime. I think, you have another service that can tell the which strategy to use (based on runtime parameters).

A rough implementation could look like that:

public Worker {
  private Operator operator;    // your actual operator strategy
  public void setOperator(Operator actualOperator) {
    this.operator = operator;
  }

  public doSomething() {

     while(stopCriterion) {
       Operator operatorForThisIteration = operator;  // pick the injected service
       operatorForThisIteration.doSomething;
     }
  }
}

And another service, the one that can inject dependencies to worker instances, would maintain a list of all worker instances, implement some logic to choose a new service and inject in into all (or some) workers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!