A common use case is to have some kind of factory classes defined:
public abstract class IFactory {
public abstract Object getObject(String input);
}
An implementation factory should probably provide the object based on the input.
For example:
public class FactoryImpl {
private static instance = null;
public IFactory instance() {
if (instance == null) {
return new IFactory() {
@Override
public Object getObject(String input) {
return new Object(); //based on input data in real
}
};
}
}
}
This is cumbersome, so I'd like to refactor the code using lambda expressions.
But what is the preferred way?
I could imagine the following two alternatives:
public class FactoryImpl {
public IFactory instance() {
if (instance == null) {
return (data) -> new Object(); //explicit using new operator
}
}
}
public class FactoryImpl {
public IFactory instance() {
if (instance == null) {
IFactory factory = Object::new;
return (data) -> factory.getObject(); //using method reference
}
}
}
Is there an approach that should be preferred (eg for readablility or conventions)?
You are making your life unnecessary complicated.
If you have an interface like
public interface IFactory {
Object getObject(String input);
}
you may implement it as
public class NameIsIrrelevant {
public IFactory instance() {
return input -> new Object();
}
}
without thinking about the singleton pattern. While it is not guaranteed, the implementation does return a singleton implementation here as it always does for non-capturing lambdas.
This is not an iron-hard guaranty but on the other hand, there is no harm if the returned instances are not singletons…
This has nothing to do with the question whether you will use lambda expressions or method references.
If the type your factory ought to construct has a constructor which accepts the factory’s input as a parameter value, you may implement the factory as
public class NameIsIrrelevant {
public IFactory instance() {
return TheType::new;
}
}
but that’s only a minor optimization or rather a stylistic choice; it does not change in any way how the factory works. If there is no such constructor, there is no point in trying to use a method reference anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With