views:

52

answers:

1

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 a Customer from the database,
  • KillCustomer - not static, removes a customer from the database.

If I understand well,

  1. LoadCustomer is a good candidate to be put into a factory class.
  2. What about CreateCustomer? I suppose that it may be put into a factory class. Is that right? If not, the static CreateCustomer method will change the database state, then call CustomerFactory.LoadCustomer. IMHO, this is bad design: a given object don't have to know anything about her own factory.
  3. 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. Calling KillCustomer 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?

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?

+3  A: 

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 Customer and some details about the data used to create a customer determined which kind of customer was made, then CreateCustomer would be a great candidate for a factory method. The same with LoadCustomer since presumably you aren't completely sure exactly which sort of customer is being stored in the database.

But KillCustomer is 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.

Omnifarious