Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

cbrooks (3267)

cbrooks
  (email not shown publicly)

Journal of cbrooks (3267)

Friday July 19, 2002
07:56 AM

The Factory Pattern

[ #6475 ]
I am trying to find an elegant method of solving the following (recurring) problem: I have a class (Facility.pm) that represents eldercare facilities that is used in the following way:

my $facility = new Facility( unique_id, facility_type );
print $facility->get_name;

The constructor for this class can accept either:
  • a unique id and the type of facility to be instantiated (in which case the constructor knows how to pull the relevant information from a database)
  • a hash ref with the data used to instantiate the object

The class is quite useful when dealing with a single facility, but I would like to make it more useful. Rather than having to know a unique id, or the actual values that will be used by the object, I'd like to be able to pass in (for example) a city and a state, and get an arrayref of Facility objects for every facility in that city and state.

Now, I have noticed that the class names for many classes in Java match the pattern <Classname>Factory, and I thought "Aha! I could create a FacilityFactory class, which might have the following usage:"

my $factory = new FacilityFactory(
    facility_type => 'NursingHome',
    city => 'Birmingham',
    state => 'AL'
);

foreach my $facility ( @$factory ) {
    print $facility->get_name;
}

FacilityFactory would know how to translate its parameters into valid SQL, query the database, and return an arrayref of instantiated Facility objects.

Well, okay that would work, but then I decided to go see if this was actually consistent with the <Classname>Factory pattern that I have seen used in Java. And wouldn't you know, it isn't. The Factory pattern is used when you can't know until runtime which type of class you need to instantiate. The Factory class encapsulates the logic for selecting one of these child clases, is implemented as an abstract base class. Kind of a different beast than what I was attempting.

So here's my question. What is the best way to crack this nut? Here are my options as I see them:

  • Ignore the formal definition of the Factory pattern because hey, this does what I need;
  • Essentially ignore the formal definition, rename my class FacilitySet and move on
  • Make the Facility class more flexible, so that it represents one or more facilities, rather than just one;
  • Punt, and hope that one of you will pick up the ball....

Thanks for any comments.

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.