Describing the question without code:
If a Class' operation (that otherwise fulfills structure of Factory Method -pattern,) returns a copy of an existing object's reference, which is fetched by another object's operation, and used by it's known type, instead of instantiating a new object - can it be classified as a Factory Method?
In addition, if it is deemed as not-a-factory-method; Does it matter whether the process of creating a new instance of a ConcreteProduct happens within the ConcreteCreator, or not? (Taking account that in JAVA you always end up returning a reference, so only pragmatic difference would be that we're creating a new instance instead of using an existing one - but does this make the whole difference whether we have a "Factory Method" or not?)
A minimal example in JAVA:
interface Product { ... }
class ConcreteProductA { ... }
class ConcreteProductB { ... }
class ProductHolder
{
private Product foo;
/*
* May return an instance of either ConcreteProductA or ConcreteProductB
* Sets foo null, for attempting to mimic a composition relationship to holder, foo being moved into another composition relationship
*/
public Product getProduct() {
Product reference = foo;
foo = null;
return reference;
}
public void setProduct(Product foo) {
this.foo = foo;
}
}
interface Creator { public Product createProduct(); }
class ConcreteCreatorA implements Creator
{
@Override
public Product createProduct(ProductHolder holder) {
return holder.getProduct();
}
}
Edit: Noting that I intentionally left unchecked whether method returns null or not, does this have any relevance to the question?
(my) Arguments for:
- (Most of all) It fulfills the GoF: Design Patterns -book's Factory Method -part's "Applicability" -section's paragraph #1:
"(Use Factory Method -pattern, when) ..CreatorClass does not know in advance, from which ProductClass the instantiated objects must be."
[Possibly an incorrect set of words; I use a translated version.]
- It does allocate memory, for holding the reference to the chosen object.
- It is typecasted to it's type, known by Creator -class.
- It is defined within ConcreteCreator -class (referencing GoF: Design Patterns -book's UML diagram).
(my) Arguments against:
- It uses an existing object, therefore it doesn't create a new instance. (Is this necessary, semantics-wise?)
- It copies a specific object, not a specific class. (Given instance may have existing altered states, as opposed to a newly constructed instance)
Related yet separate questions' posts:
General answer to his/her question: Singleton Factory