设计模式名称: 是工厂吗?
下面的类展示了与真实用例类似的内容。它始终为同一线程返回相同的实例。
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();
}
}
你会怎么称呼它?是“工厂”吗? “价值持有者”? “线程本地存储”?
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"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有些人简单地将其称为ThreadLocal 模式。另一个已知名称是线程本地存储 (TLS)。
Some simply called it the ThreadLocal Pattern. Another known name is Thread-local Storage (TLS).
不是工厂。看起来像一个单身人士。工厂的想法是创建基于基类的对象。
Not a factory. looks like a singleton. The idea of the factory is to CREATE objects dirrived on a based class.
getInstance()
绝对是一个工厂方法。有人可能会为整个每线程伪单例取一个很酷的名称,但由于这种情况太罕见而无法广泛相关,因此拥有它没有任何价值。 “每线程单例”听起来对我来说是最好的选择。
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.