Design pattern name: Is it a factory?
-
27-09-2019 - |
Question
The following class shows something similar to a real use case. It returns always the same instance for the same thread.
public class LookingForName {
private static final ThreadLocal<Something> threadLocal =
new ThreadLocal<Something>(){
@Override
protected Something initialValue() {
return getSomethingSpecial(); // not relevant
}
};
/**
* @return always the same instance of "Something" for the current thread.
*/
public static Something getInstance() {
return threadLocal.get();
}
}
How would you call it? Is it a "factory"? A "value holder"? "ThreadLocalStore"?
Solution
Some simply called it the ThreadLocal Pattern. Another known name is Thread-local Storage (TLS).
OTHER TIPS
Not a factory. looks like a singleton. The idea of the factory is to CREATE objects dirrived on a based class.
getInstance()
is most definitely a factory method.
Someone might have compe up with a cool name for the entire per-thread-pseudo-singleton, but since it's too rare a case to be widely relevant, there is no value in having it. "Per-thread singleton" sounds like the best option to me.
For complete reference of Factory Method design pattern and other related pattern, refer this article,
http://www.codinguide.com/2010/04/factory-pattern.html
Regards,