I'm just beginning to grasp the concept of factories, and want to use them in my next project (I'm using dependency injection, so using factories will make object instantiation easier). Some basic questions I have:

  1. Does it make sense to have one factory class per application layer (GUI, BLL, DAL), per class, or just one factory class for everything?
  2. What is a typical naming convention for factory classes?


  1. If I create a factory per class, in a .Net project, should I simply create one class file called Factories.cs to house all of my factory classes? If not, what would be a better approach?

Following the seperation of concerns principle, each class should only be 'concerned' about a small portion of the application. Applying this to factory classes, a factory class should only be concerned about creating objects of one particular type.

In practice this means:

  • One factory class per interface/abstract class/base types that are created.
  • One source file per class, so one source file per factory.

Conventions are usually decided on per project or team, but I use the following convention:

  • Suffix factories with 'Factory'.
  • Prefix them with the type they create. (e.g. SomeTypeFactory)
  • Usually factories are done per class, or rather per interface

  • I Usually call them [ClassName]Factory

  • How would you organize your factories classes? All in one Factories.cs file? Or one file per factory class (that seems like a bit much...)? – sooprise Jun 13 '11 at 13:57
  • And where do you put them? At the same level of the concerned classes or in a sub directory named Factory or something like that? – user2567 Jun 13 '11 at 13:59
  • No, one factory per file. In general you shouldn't have more than one class per file. It's only confusing and bad practice from a source control perspective etc. Where to put them is a matter of taste but I tend to put classes/interfaces/enums/base classes/singletons/factories etc in separate sub-directories – Homde Jun 13 '11 at 15:06
  • In your classes sub-directory, do you have separate sub-sub-directories for BLL and DAL layers? – sooprise Jun 13 '11 at 15:11
  • 3
    @sooprise: Have you considered the possibility that you are trying to use factories for nothing other than the sake of using factories? A factory should be used when object creation is complicated enough to warrant implementing it in its own class. Using factories everywhere would be unnecessary. – quentin-starin Jun 13 '11 at 19:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.