如何在OSGi中编写工厂模式?

问题描述 投票:0回答:1

我有多个Impl类实现相同的服务。我需要在osgi中编写一个工厂类,我应该编写getter方法来返回适当的Impl对象。以下是我试过的代码。我在工厂上课时很震惊。还有什么想法吗?

public interface ServiceA {
   public void display();
}

@Component (description = "Test1 service", ds = true, immediate = true)
@Service (value = {ServiceA.class})
class Test1 implements ServiceA{

      public void display(){
        Log.debug("Test1");
      }
}

@Component (description = "Test2 service", ds = true, immediate = true)
@Service (value = {ServiceA.class})
class Test2 implements ServiceA{

      public void display(){
        Log.debug("Test2");
      }
}

//How to write factory ?
class Factory{

    public ServiceA getObject(String testType){
         if(testType.equals("Test1")){
             return Test1;
         }
         else{
             return Test2;
         }
    }
}
osgi service-factory
1个回答
1
投票

虽然目前尚不清楚您的应用程序打算如何使用这些不同的服务实现,但一种方法是使用服务属性,然后在服务使用者实际引用这些服务时需要该属性,例如:

@Component (description = "Test1 service", ds = true, immediate = true)
@Service (value = {ServiceA.class})
@Property (name = "type", value = "test1")
class Test1 implements ServiceA{
    // ...
}

@Component (description = "Test2 service", ds = true, immediate = true)
@Service (value = {ServiceA.class})
@Property (name = "type", value = "test2")
class Test2 implements ServiceA{
    // ...
}

...在消费者方面,您只需为参考添加服务选择标准,例如:

@Component (...)
class MyConsumer {
    // ...

    @Reference(target="(type=test2)")
    ServiceA testService2;

    // ...
}

不需要工厂! :)

有关更多信息,请查看this little article

如果需要根据运行时服务请求属性动态路由到特定服务实现,您还可以保留对所有服务实现的引用,并使用所需属性映射它们以进行快速选择,例如:

@Component (...)
class MyConsumer {
    // ...
    private final Map<String, ServiceA> services = // ...

    @Reference(
            cardinality = ReferenceCardinality.MULTIPLE,
            policy = ReferencePolicy.DYNAMIC,
            service = ServiceA.class,
            target = "(type=*)"
    )
    public void addServiceA(ServiceA instance, Map properties) {
        service.put(String.valueOf(properties.get("type")), instance);
    }

    public void removeServiceA(Map properties) {
        service.remove(String.valueOf(properties.get("type")));
    }

    // ...
}
© www.soinside.com 2019 - 2024. All rights reserved.