P
- the type of the products to create.@Immutable public abstract class LocatableFactory<P> extends LocatableProvider<P> implements Factory<P>
P
.
In the following example the type parameter is specified as
StringBuilder
:
package com.company.spec;
import net.java.truecommons.services.LocatableFactory;
public abstract class StringBuilderFactory
extends LocatableFactory<StringBuilder> {
}
An implementation could now implement this service as follows:
package com.company.impl;
import com.company.spec.StringBuilderFactory;
public class GreetingFactory extends StringBuilderFactory {
\@Override
public StringBuilder get() {
// Return a new instance on each call!
return new StringBuilder("Hello Christian!");
}
}
Next, the implementation needs to advertise its service by providing a file
with the name META-INF/services/com.company.spec.StringBuilderFactory
on the run time class path with the following single line content:
com.company.impl.GreetingFactory
If multiple factory services are locatable on the class path at run time, the service with the greatest priority gets selected.
Finally, a client could now simply compose a factory according to the
StringBuilderFactory
specification by calling:
package com.company.client;
import net.java.truecommons.services.Locator;
import com.company.spec.StringBuilderFactory;
public class Main {
public static void main(String[] args) {
Locator l = new Locator(Main.class); // specify calling class
Factory<StringBuilder> f = l.factory(StringBuilderFactory.class);
StringBuilder b = f.get(); // create product
System.out.println(b.toString()); // use product
}
}
Note that multiple calls to f.get()
would always return a new
product because f
is a factory, not a container.
Implementations should be thread-safe.
Locator
Constructor and Description |
---|
LocatableFactory() |
Copyright © 2012–2018 Schlichtherle IT Services. All rights reserved.