Patterns 101: The Factory

By Joe Hubert
Page 2 of 4

Example: My Tasks

Being a software architect, I can't remember what I'm supposed to do without writing it down, so I've composed a program to list my daily tasks based on what day of the week it is.

Here is my task list:

  • Monday: Move the trash to the curb
  • Tuesday: Put out the recyclables
  • Wednesday: Watch "Lost"
  • Thursday: Move the trash to the curb
  • Friday: Buy beer

And here is the class I've written to display those tasks:

Listing 1: MainProcedural.java
import java.util.Date;

public class MainProcedural {

    public static void main(String[] args) {
        Date date = new Date();
        int weekday = -1;
        MainProcedural taskMgr = new MainProcedural();

        //-- Allow the weekday to be set by a parameter so we can test the program
        if (args.length >0 ) {
            try {
                weekday = Integer.parseInt(args[0]);
            }
            catch (Exception e) {
                System.out.println("Parameter must be 1 - 7");
            }
        }
        else {
            weekday =  date.getDay();
        }

        switch (weekday) {
            case 1:
                taskMgr.showMondayTasks();
                break;
            case 2:
                taskMgr.showTuesdayTasks();
                break;
            case 3:
                taskMgr.showWednesdayTasks();
                break;
            case 4:
                taskMgr.showThursdayTasks();
                break;
            case 5:
                taskMgr.showFridayTasks();
                break;
            default:
                System.out.println("No tasks on the weekend.");
        }
    }

Note that this class doesn't give me any direction on the weekends. After some time, I decide to extend it to include my weekend tasks:

  • Saturday: Cut the lawn
  • Sunday: Call Mom.

The changes I have to make are pretty straight forward:

  • Change the switch statement to include cases for Saturday and Sunday.
  • Write new methods to handle the task displays: showSaturdayTasks()and showSundayTasks().

There's an object oriented guideline that I've found to be pretty consistently valid: if you're asking a lot of questions about the nature of your objects in the operational parts of your application, you probably aren't taking an object oriented approach to the problem. In other words, if you see a lot of "if", "switch", and "instanceof" statements when you're dealing with your objects, there's a good chance you have some room to improve your design.


Feedback

Articles
Factory 101

Strategy 101