问题
Ok, this is entirely semantics and naming...but is my implementation still a factory pattern if it's used, for example, to return a singleton instance?
That is, is it still proper to call it a factory if it only constructs a new instance once:
// am I still a factory?
public static class SomeFactory
{
[ThreadStatic]
private static object _currentSomething;
public static object Something
{
get { return _currentSomething ?? _currentSomething = new object(); }
}
}
回答1:
It looks factory and I think that is the best of the similarities. It seems like you are trying to make a Singleton Factory. But there is something about it that doesn't feel right.
Maybe because it is only ever going to return an object...unless you are going to do something different. What are you planning on doing with this? Ah...I see, as @LukeH says, a Thread Singleton.
EDIT: My personal take is that, as written, it is a pattern for a pattern. The code can do nothing but return an object and only an object. This is how I modified the code for personal style. Please correct me if I'm wrong with my interpretation:
static void Main()
{
object obj1 = SomeFactory.Something;
Console.WriteLine("obj1 hash:{0}", obj1.GetHashCode());
object obj2 = SomeFactory.Something;
Console.WriteLine("obj2 hash:{0}", obj2.GetHashCode());
Console.Read();
}
public static class SomeFactory
{
[ThreadStatic]
private static object _currentSomething;
public static object Something
{
get
{
if (_currentSomething != null)
{
return _currentSomething;
}
else
{
_currentSomething = new object();
Console.WriteLine("Returning new object - hashcode: {0}", _currentSomething.GetHashCode());
return _currentSomething;
}
}
}
}
Writelines confirm, however rudimentary, that I only get one object on the main thread. Cool...but what about using other custom objects?
2nd Edit:
I would consider something like:
public static class GenericFactory<T> where T : new()
{
[ThreadStatic]
private static T _currentSomething;
public static object Something
{
get
{
if (_currentSomething != null)
{
return _currentSomething;
}
else
{
_currentSomething = new T();
Console.WriteLine("Returning new {0} - hashcode: {1}", _currentSomething.GetType(), _currentSomething.GetHashCode());
return _currentSomething;
}
}
}
}
回答2:
Yep, its just a singleton factory.
来源:https://stackoverflow.com/questions/4372703/is-it-still-a-factory-if-it-shares-instances-across-requests