Hi,
I'm not really sure to understand completely the factory pattern.
Let's say I have a class Customer
which has basically the following methods:
CreateCustomer
- static, creates a customer from scratch and adds it to the database,LoadCustomer
- static, loads an instance of aCustomer
from the database,KillCustomer
- not static, removes a customer from the database.
If I understand well,
LoadCustomer
is a good candidate to be put into a factory class.- What about
CreateCustomer
? I suppose that it may be put into a factory class. Is that right? If not, the staticCreateCustomer
method will change the database state, then callCustomerFactory.LoadCustomer
. IMHO, this is bad design: a given object don't have to know anything about her own factory. KillCustomer
seems to me a very bad candidate for a factory: it acts on an already created object, rather than creating one. On the other hand:- If a non-static method removes the customer from the database, the object (from which
KillCustomer
was called) still exists. This is quite strange to see an object committing suicide on database level and still remaining on business level. CallingKillCustomer
from factory would be more reasonable on this level. For example, if the object is cached in application, the factory may remove it both from database and from cache. - Putting in different classes the method which creates an object and the method which removes it seems strange too. Why can factory just build something, and never destroy what was built?
- If a non-static method removes the customer from the database, the object (from which
Last but not least, let's say customers are cached in application. Who is responsible to manage cache? IMO, the factory must do it: it creates the objects, so it is a good candidate to choose if a new object with properties populated from database must be loaded, or if the object already exists in cache.
So, what's right and what's wrong in what I'm thinking about factory pattern?