简体   繁体   English

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

[英]Design pattern name: Is it a factory?

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"? “ ThreadLocalStore”?

Some simply called it the ThreadLocal Pattern . 有人简单地称其为ThreadLocal Pattern Another known name is Thread-local Storage (TLS) . 另一个已知的名称是线程本地存储(TLS)

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. getInstance()绝对是工厂方法。

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, 有关Factory Method设计模式和其他相关模式的完整参考,请参考本文,

http://www.codinguide.com/2010/04/factory-pattern.html http://www.codinguide.com/2010/04/factory-pattern.html

Regards, 问候,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM