Patterns 101: The Factory

By Joe Hubert
Page 4 of 4

Here's the important part...

The reader might think: "So basically you just moved the switch statement into the factory and handled the messages in separate classes instead of using specific methods. Is that such a big deal?"

Response: Yeah, it is. That's the whole idea. It may not seem like such a big deal with this trivial example (in fact it may seem like more work), but as the core application gets more complicated, and the scope of the application grows, the organization of application code is a very big deal. The second approach is more suitable for teams of developers: each developer could work on his or her DayTasks subclasses without worrying about dependencies, working on the same file concurrently, or duplicating effort. And imagine that you got your core classes to the point where they were stable, handling exceptions where necessary, logging, and performing other base functionality well. Isn't it nice that you extended the functionality of the system at large without touching the core class? That's why this approach is considered a framework: the functionality was extended by adding a class that "plugged in" to the existing model - a class that wasn't even conceived by the time the core class stabilized.

What are the major points?

  • The approach we took here is founded on polymorphism. The core class deals with DayTasks and the classes returned by the factory are DayTasks because each class extends DayTasks. If that is not completely clear, read up on polymorphism. Look for some basic example, like the ... Shape.draw().
  • The purpose of a factory class is to isolate the decision-making code of your system. Of course you may need separate factories if you're dealing with a range of object types.
  • We extended the functionality of our program without changing the core classes (class, in this case), and that's a good thing.

So that's it. I think by having a grasp of the "why" when it comes to patterns, you can understand "what" they are. As I mentioned earlier, you might have to implement an example similar to the one presented here to fully understand and appreciate the approach. Look for some application you've written that has a switch statement or a series of "if/else" conditions. Look at the statements that are called in each "if/else" block and think about the base classes and extended classes that can perform the necessary operations. You may never code an application the same old way again.

-Joe


Download the example source code
Feedback

Articles
Factory 101

Strategy 101