设计模式名称: 是工厂吗?

发布于 2024-09-13 11:03:37 字数 595 浏览 3 评论 0原文

下面的类展示了与真实用例类似的内容。它始终为同一线程返回相同的实例。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

微凉徒眸意 2024-09-20 11:03:37

有些人简单地将其称为ThreadLocal 模式。另一个已知名称是线程本地存储 (TLS)

Some simply called it the ThreadLocal Pattern. Another known name is Thread-local Storage (TLS).

有木有妳兜一样 2024-09-20 11:03:37

不是工厂。看起来像一个单身人士。工厂的想法是创建基于基类的对象。

Not a factory. looks like a singleton. The idea of the factory is to CREATE objects dirrived on a based class.

晨曦÷微暖 2024-09-20 11:03:37

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文