I was thinking about a design problem a co-worker has and my implementation idea seems reasonable, but strange. I'm sure there's a pattern or something which describes this, but I'd love feedback on the idea.

Imagine that you have "products". A product might exist, but it also might be a brand-new product being created (potential products). What I'm thinking is a factory 'Product' class. You start by creating the object:

  my $whip = Product->new('whip');

If we already have a 'whip' product, that returns a Product::Real class. Otherwise, it returns a Product::Potential class. Let's say it doesn't exist, we want to be able to do this:

  $whip->create;

At that point, it gets registered, stored in the database, and can get assigned to a client. It then reblesses itself into a Product::Real class. Attempting to call create() again is a fatal error because real products don't have that method, but you do gain a delete() method which unregisters the product and removes it from the database. The class then switches back to a Product::Potential instance.

Potential products actually have quite a bit of behavior unique to them, as do real products. I don't want one big fat class with a bunch of procedural if/else code to know if the product exists or not.

What is this design usually called (aside from 'stupid')? Basically, we have a factory class which instantiates subclasses which might mutate into another subclass depending on their state.

The idea sort of bugs me because the subclasses have significantly different behaviors and methods and silently transform themselves at runtime. Is there a better solution to this problem?

Cheers,
Ovid

New address of my CGI Course.


In reply to Reblessing yourself by Ovid

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.