服务装载机构造

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

所以,这里是我的结构

interface FactoryService {
    Foo createFoo(int a, String b);
}

@AutoService(FactoryService.class)
class SomeFactory implements FactoryService {
    public Foo createFoo(int a, String b) {
        // How to implement service loader here, which loads Foo
    }
}

interface Foo {
    void opsForFoo(InputStream s, OutputStream o)
}

class FooImpl implements Foo {
    // Constructor
    public FooImpl(int a, String b) {}
    public void opsForFoo(InputStream s, OutputStream o) {
        // perform operation here
    }
}

我怎样才能实现SomeFactory类的ServiceLoader?我的问题是FooImpl发生在两个值从构造函数。我只是做new FooImpl(a, b),但它是正确的吗?展望未来有可能实现Foo其他类

java oop
1个回答
0
投票

在基础设施的ServiceLoader的一点是,你可以定义任意数量的是无论你正在做的对的ServiceLoader实现类,它们可以在classpath的任何地方。

例如,在你的榜样,你要serviceload“FactoryService”(而不是foo!),所以,你的代码可以提供任何数量的FactoryService的实现,不管是做服务的负担将得到每一个这样的1个实例FactoryService类,你已经设置了。在这里,你设立一个这样的类,称为“SomeFactory”。

这种特殊的变种FactoryService(你的“SomeFactory”)会在被调用(在被称为其createFoo方法),返回FooImpl的一个实例。

如果,有一天,有富的不同IMPL,你有两个选择:

[1]扩大你的SomeFactory类返回依赖于任何你想要的(它的代码,毕竟,天空的极限),这样不同的IMPL。例如:return a < 0 ? new NegativeFooImpl(Math.abs(a), b) : new PositiveFooImpl(a, b);

[2]制造也实现FactoryService的第二类。

这里的FactoryService的总体布局是一点点奇怪:既然有,比方说,10个factoryservices,这里有什么想法?一些请求时,无论是做serviceloading为factoryservice调用所有10个服务,生产10个FOOS,然后..拿起一个?想必FactoryService接口需要一定的javadoc着,说:/** If a and b are such that this call is not for you, return null. The code that loads foos will go with the Foo value returned by the first implementation of FactoryService called that returns non-null. */

例如,最后一个看起来有点像:

public class FooMaker {
    ServiceLoader<FactoryService> fooFactories = ServiceLoader.load(FactoryService.class);

    public Foo createAFoo(int a, String b) {
        for (FactoryService factory : fooFactories) {
            Foo foo = factory.createFoo(a, b);
            if (foo != null) return foo;
        }
        return null;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.