Update: added a more intuitive example here


Lets say we have two classes Container and Element

and you can

my $cont = Container->new(); my $elem = Element->new('name'); $cont->add_elem($elem); # method chaining $cont1->get_elem('name')->do_something(); # identical to $elem1 = $cont1->get_elem('name'); $elem1->do_something(); # *

For this to work does $elem2 obviously need to know that it belongs to $container.

So it's N->1 : N Element -> 1 Container

and $elem1 == $elem

with updated property $elem->{member_of}=$cont Now after using this for a long time new requirements arise and Elements need to belong to multiple Containers.

So now it's N->M : N Element -> M Container

Clearly the old model with $elem2 == $elem doesn't work anymore because

$elem2 = $cont2->get_elem('name'); can't be member_of two different containers to allow method chaining

I don't think that $elem1 and $elem2 should belong to class Element either, but to a "wrapper" class ContainerElement referencing $elem, i.e. $elem1->{master}=$elem

Then I could think of many solutions, some involving inheritance, some AUTOLOAD to make sure that

$elem1->do_something(...) always does $elem1->{master}->do_something(..)

without hardcoding all methods.

I don't wanna reinvent the wheel and I'm already starting to worry too much about performance so here the question ...

What are the usual OO-Patterns to solve this? :)

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery

update

*) OK Sorry, do_something() is doing something with the relation $cont <- $elem like set_weight($cont,$elem)


In reply to OO Pattern Container x Elements and Method Chaining by LanX

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.