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 aCustomerfrom the database,KillCustomer– not static, removes a customer from the database.
If I understand well,
LoadCustomeris 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 staticCreateCustomermethod 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. KillCustomerseems 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
KillCustomerwas called) still exists. This is quite strange to see an object committing suicide on database level and still remaining on business level. CallingKillCustomerfrom 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?
Factory is not for building things. It’s for building things when you don’t know exactly what you’re going to build. In my opinion, all of your methods are poor candidates for a factory.
Now, if you had a whole big bunch of different kinds of customers in an inheritance hierarchy rooted at
Customerand some details about the data used to create a customer determined which kind of customer was made, thenCreateCustomerwould be a great candidate for a factory method. The same withLoadCustomersince presumably you aren’t completely sure exactly which sort of customer is being stored in the database.But
KillCustomeris still a bad candidate. And that’s because it should just be a virtual method. Then it knows exactly which kind of customer it was called on.