Ram
Ram

Reputation: 11644

Factory Design pattern : Can factory hold the instances?

I need to create multiple instance of the same class for which it has been decided to use factory pattern. We need to provide the querying capabilities on the instances created by the factory.

So as per the standards of factory pattern, can a factory hold the objects that it has created? or I need to create another component which will allow the querying on these instances?

Upvotes: 2

Views: 1043

Answers (2)

willcodejavaforfood
willcodejavaforfood

Reputation: 44083

It certainly COULD hold the object it has created, but that would mean that the factory has two responsibilities. It would be better if you created a repository class that is responsible for keeping references to the created objects. The repository class could also use the factory to create new instances if it does not already have an object with that ID.

Upvotes: 7

Nikos Baxevanis
Nikos Baxevanis

Reputation: 11201

In general the owner of your objects should perform tasks associated with freeing or releasing resources allocated by the objects it creates.

At your example, it is the factory class (or whatever pattern you choose) that will perform these tasks.

Upvotes: 0

Related Questions